MATLAB: The variabel ‘total’ seems to change size on every loop….-A while loop problem

absolutefprintfproblemtotalvariablewhilewhilellop

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)

Best Answer

You want to approximate pi/4 by:
1 - 1/3 + 1/5 - 1/7
But you code produces:
1 - 1/3 + (((-1)^3)/(2*3+1)) + (((-1)^4)/(2*4+1))
which is:
1 - 1/3 - 1/7 + 1/9
Therefore 1/5 is missing in the result. You have to set k=2 before the loop.
The MLint-warning, that total changes it size in each iteration is not an error. It reduces the run-time very much, but I do not assume, that this is a problem for a homework. So simply ignore this message. But keep in mind, that growing arrays will become a serious problem in real-world programs. You can search for the term "pre-allocation" in this forum.