Filter löschen
Filter löschen

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 Ansicht (letzte 30 Tage)
%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);

Akzeptierte Antwort

jgg
jgg am 5 Jan. 2016
Bearbeitet: jgg am 5 Jan. 2016
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 Kommentare
MF
MF am 5 Jan. 2016
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 am 6 Jan. 2016
Bearbeitet: jgg am 6 Jan. 2016
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Time Series finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by