필터 지우기
필터 지우기

I am trying to plot, at x=pi/4, the variation of the error percentage along h (h increments from 0.01 to 0.5), using the first order central difference method for function f(x)=sinx. Can't figure out what's wrong with the code. Any help please?

조회 수: 1 (최근 30일)
%t(n) is the approx.value
z = cos(pi/4);%Exact value
n=0
for h=0.01:0.01:0.5;
n=n+1;
t(n) =(sin((pi/4)+h))-(sin(pi/4)-(h))/((2*h));
Percent_Error(n) = abs(t(n)-z./z)*100;
end
hold on
plot (t, Percent_Error);

채택된 답변

jgg
jgg 2016년 1월 5일
편집: jgg 2016년 1월 5일
You need to be more careful about your brackets:
z = cos(pi/4);%Exact value
n=0
for h=0.01:0.01:0.5;
n=n+1;
t(n) =(sin((pi/4)+h)-sin((pi/4)-h))/((2*h));
Percent_Error(n) = abs((t(n)-z)./z)*100;
end
hold on
plot (t, Percent_Error);
The lines
t(n) =(sin((pi/4)+h)-sin((pi/4)-h))/((2*h));
Percent_Error(n) = abs((t(n)-z)./z)*100;
Both incorrectly bracketed the expression you wanted there. In the first line, you didn't divide the first term by 2h and also did not have the -h term inside the sin function. This led to the wrong value for t being calculated. In the second line, you divided z by z instead of dividing t(n) - z by z; this led to the the wrong error being calculated.
  댓글 수: 2
MF
MF 2016년 1월 5일
Thanks for your reply, like this the brackets should be OK now. However, I still can't figure out how I can code it. I really need some help.
z = cos(pi/4);%Exact value
n=0;
for h=0.01:0.01:0.5;
n=n+1;
t(n) =((sin(pi/4)+(h))-(sin(pi/4)-(h)))/(2*h);
Percent_Error(n)= abs (((t(n)-(z))./z)*100);
end
plot (t, Percent_Error);
jgg
jgg 2016년 1월 6일
편집: jgg 2016년 1월 6일
Your brackets still are incorrect:
t(n) =((sin(pi/4)+(h))-(sin(pi/4)-(h)))/(2*h);
Look at this expression (sin(pi/4)+(h)) within the first set of brackets. This is not the same as (sin(pi/4+h)) which is what you want. The bracketing in Matlab follows standard BEDMASS bracketing rules from mathematics. The expression you want should be:
t(n) =(sin(pi/4+h)-sin(pi/4-h))/(2*h)
Some tips:
  • You don't need to bracket individual variables like +(h). This can just be written as +h
  • The brackets of a function delimit what is contained in in f(x) + h is not the same as f(x+h).
For the record, the code I posted above should work.
An easy way to debug these things is to work from the inside out of your expression until you get the wrong answer. For instance, evaluate sin(pi/4)+(h) and notice it's wrong, then correct it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Time Series에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by