The variabel 'total' seems to change size on every loop....-A while loop problem
이전 댓글 표시
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
dpb
2013년 10월 15일
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
2013년 10월 15일
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
2013년 10월 15일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!