Hi, what's wrong with the following code?
=========================================================================================================x=pi/4; n=2; sum=2; while(1) m=2*n-1; sumnew=sum+(-1)^(n-1)*x^m/factorial(m); error=(sumnew-sum)/sumnew; n=n+1; sum=sumnew; if error<0.001; break end end

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 20 Mär. 2015

0 Stimmen

Try it
x= pi/4;
n = 2;
sum1 = 2;
er = 1;
while abs(er) > 0.001
m = 2*n-1;
sumnew = sum1+(-1)^(n-1)*x^m/factorial(m);
er = (sumnew-sum1)/sumnew;
n = n+1;
sum1 = sumnew;
end

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 20 Mär. 2015

0 Stimmen

If you were trying to calculate sin(pi/4), you started with the wrong values for n and sum1. For sin(pi/4) it should be the following. (As yours stands, it computes 2+sin(pi/4)-pi/4.)
x=pi/4;
n=1; % <-- Start with n = 1
sum1=0; % <-- Start with sum1 = 0
while(1)
m=2*n-1;
sumnew=sum1+(-1)^(n-1)*x^m/factorial(m);
error=abs((sumnew-sum1)/sumnew); % <-- Also this should be absolute value
n=n+1;
sum1=sumnew;
if error<0.001; break end
end
[Note: Like Andrei, I substituted 'sum1' for 'sum' because the latter symbol is reserved for matlab's 'sum' function.]

3 Kommentare

B
B am 20 Mär. 2015
Bearbeitet: B am 20 Mär. 2015
Thanks everyone. But in the following code where I have only changed while(1)-->while.., I'm getting the correct answer. Why is that?? ================================================================================= x=pi/4; sum1=x; n=2; error=5; while error>0.001 m=(2*n)-1; sumnew=sum1+(-1)^(n-1)*x^m/factorial(m); error=(abs(sumnew-sum1)/sumnew); n=n+1; sum1=sumnew; end display(sumnew)
================================================================================= I've also tried your codes, but MATLAB was stuck, could you plz check that? Thanks a lot for your help.
B
B am 20 Mär. 2015
I'm not sure if the problem is related to the computer it self. It's very slow right now..
B
B am 20 Mär. 2015
First code is working now.. Thanks Andrei Bobrov

Melden Sie sich an, um zu kommentieren.

Tags

Gefragt:

B
B
am 20 Mär. 2015

Kommentiert:

B
B
am 20 Mär. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by