While loop not ending

1 view (last 30 days)
Andrew
Andrew on 22 Jan 2012
Hello all, this is my first post on here so please forgive me if I do something wrong.
I am working on homework for one of my courses where I need to calculate how many terms of the arctangent taylor series approximation are needed to produce six significant figures of pi according to the scarborough criteria (relative error is less than .5*10^(-m) where m is the number of significant figures). Upon running my loop for around five minutes multiple times I have ended it and manually check my value for the relative error and found it to be around 7*10^(-11). My code is as follows:
%use pi=4.0atan(1) and the taylor series expansion for arc tangent about x=0
%to calculate pi to six significant figures using the scarborough criteria.
a=2; e_a=10; x=1; pi_exper(1)=20;
while e_a>.0000005
arctan(a-1)=(-1)^(a)*x^(2*a-3)/(2*a-3);
pid4(a-1)=sum(arctan);
pi_exper(a)=4*pid4(a-1);
e_a=abs(pi_exper(a)-pi_exper(a-1))/abs(pi_exper(a));
a=a+1;
end
Can anyone tell me why this loop is not working? Thank you very much in advance!
Andrew

Accepted Answer

Jan
Jan on 22 Jan 2012
As far as I can see you need less than 1274000 iterations. You do not reach them in 5 minutes, because the variables pid4, arctan and pi_expr grow in each iteration. This is extremly slow:
tic;
a = [];
for i = 1:1274000
a(i) = i;
end
toc; % Wow, this will not be reached in the next days!
Now Matlab has to allocate a new memory block in each iteration and copy the existing values. Finally sum(1:1000) * 8 bytes must be allocated and copied: 6.48 TB ! And you do this for 3 variables. A pre-allocation accelerates this:
tic;
a = zeros(1, 1274000);
for i = 1:1274000
a(i) = i;
end
toc; % 0.110002 seconds !!!
In addition calculating the sum repeatedly wastes time. It is smarter to add just the new term.
[EDITED]: The number of iteration is rounded now to allow the OP to submit his homework.
  2 Comments
Walter Roberson
Walter Roberson on 23 Jan 2012
(blanking was missed in several places; also increased the blanking as it was still pretty specific.)
Jan
Jan on 23 Jan 2012
Thanks, Walter. How an awkward mistake...
But to post running code, I've replaced the blanking by rounding now. I think, the last digit would be enough, because the OP still needs to solve the full work to obtain it.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!