The variabel 'total' seems to change size on every loop....-A while loop problem
Ältere Kommentare anzeigen
I can't see what the problem is with my while loop. I'm trying to write a while loop to calculate a converging serie. I want the loop to stop at (pi/4).
Here is the code:
y(1)=1;
y(2)=(-1/3);
total(1)=y(1);
total(2)=total(1)+y(2);
k=3;
while (abs(total(k-1)-total(k-2))>.7854)%<----any suggestions how to tell the while loop to stop when the total sum of the terms in (pi/4)?
y(k)=(((-1)^(k))/(2*k+1));
total(k)=total(k-1)+y(k); % <----here matlab says the variabel 'total' changes size...
k=k+1;
end
fprintf('The sequence converges when the final element is equal to %8.4f \n',0.7854)
fprintf('At which point the value of the series is %5.4f \n',total(k-1))
fprintf('This compares to the value of the (pi/4),%5.4f \n',(pi/4))
fprintf('The sequence took %3.0f terms to converge \n',k)
4 Kommentare
dpb
am 15 Okt. 2013
total(k)=total(k-1)+y(k); % <----here matlab says 'total' changes size...
k=k+1;
Well, when you increment k, that follows when you reference an array with a larger subscript.
What you really want are only two terms, present and previous. Each iteration replace the present with the previous plus the new term and save the new in the old for the next iteration.
Britney
am 15 Okt. 2013
Try
>> p4=p/4; n=0; s=1; t=1; d=3;
>> while abs(s-p4)>0.001,t=-t;s=s+t/d;d=d+2;n=n+1;end,s,n
s =
0.7844
n =
249
>>
and work thru what it's doing, and how...
Britney
am 15 Okt. 2013
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Mathematics finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!