Estimating pi using while loop for specific tolerence.
이전 댓글 표시
So my task is to calculate an estimate of pi within a specific tolerence using a while loop. For a tolerence up to 10^-5, my code runs fine however anything above that and the number of iterations it takes to be within tolerence is far too high.


The 'A' matrix is used to store the Nth iteration and it's respective pi-estimate value to be used for another part of the assignment. I've attached images of my code and the summation formula I am supposed to use. I'm hoping someone can provide a tip and show me where I'm going wrong here & how to bring the number of iterations down. Thanks for your help.
댓글 수: 2
KSSV
2016년 11월 9일
I don't think there is any issue. It is obvious that the more tolerance, the more closer the value and the more it needs N and the more iterations it takes.
Jose Escobar
2016년 11월 9일
채택된 답변
추가 답변 (2개)
Roger Stafford
2016년 11월 9일
0 개 추천
The difference between the finite sum 1+1/4+1/9+...+1/N^2 and the infinite sum is proportional to 1/N. Therefore each time you divide the tolerance by ten you multiply the required number of terms in the finite sum by ten. Thus, if you are required to use this approximation, you are stuck with this kind of increase in the needed iteration count.
However you can reduce the time required by not dividing by 6 and taking the square root at each step, but only when you want to to check the answer. That is, you could take a thousand steps, for example, and only then divide by 6, take the square root, and check the answer. That would save a lot of useless repetitive computation.
Guillaume
2016년 11월 9일
Please don't post picture of your code, we can't copy/paste it. There's a {} Code button to format pasted text as code.
Roger has already explained why there's not much you can do about the runtime of your code, it's tied to the algorithm you use. I'm just going to point out that you have one obvious slow down in your code:
for ii = 1:N %gaah! can't copy paste!
A(N, 1) = N;
A(N, 2) = PiSum;
end
This just copy N times the same two values in the same two elements of A. The only effect of this loop is to make each iteration slower than the previous one.
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!