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