Azzera filtri
Azzera filtri

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 visualizzazione (ultimi 30 giorni)
%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);

Risposta accettata

jgg
jgg il 5 Gen 2016
Modificato: jgg il 5 Gen 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 Commenti
MF
MF il 5 Gen 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 il 6 Gen 2016
Modificato: jgg il 6 Gen 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Time Series in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by