필터 지우기
필터 지우기

While loop not ending

조회 수: 2 (최근 30일)
Andrew
Andrew 2012년 1월 22일
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

채택된 답변

Jan
Jan 2012년 1월 22일
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
Walter Roberson
Walter Roberson 2012년 1월 23일
(blanking was missed in several places; also increased the blanking as it was still pretty specific.)
Jan
Jan 2012년 1월 23일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by