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);
0 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Line Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!