While loop to estime pi
이전 댓글 표시
Hi. I am solving a very hard problem, I need professional help.
I am beginner.
I need to estime pi with five correct decimals (3.14159) with a while loop. I also need to estimate pi with a specific sum:
the sum have formula:
So the question is: how many terms of this sum do we need to have to estime pi with five correct decimals.
This is my code:
n=0;
pi=0;
k=4*((-1)^n/(2*n+1));
while abs(k-pi)<0.5*10^-5
n= n+1;
pi=pi+k;
k=4*((-1)^n/(2*n+1));
end
pi
n
Please help. :)
댓글 수: 2
S. Walter
2020년 11월 3일
You are overwriting the variable pi, which is a Matlab variable. You probably want to rename it to something else, like p.
John D'Errico
2020년 11월 3일
While using the variable pi to contain the result is a bad idea in general, it is not the problem.
답변 (1개)
John D'Errico
2020년 11월 3일
A hint as to the major problem...
Your loop is defined by:
while abs(k-pi)<0.5*10^-5
So as long as this is TRUE, the loop will continue.
But do you really want it to be true? In fact, it will fail immediately. Your loop will never even start, never even make one iteration.
Anyway, it is not k that approximates pi. k is just the term getting added in. Perhaps this might be more appropriate:
while abs(k) > 0.5*10^-5
By the way, you might want to learn about scientific notation. Thus, what does 0.5e-5 represent in MATLAB?
Anyway, simply testing the extra term getting added in does not truly insure the series has converged to pi to 5 digits.
카테고리
도움말 센터 및 File Exchange에서 Parallel Computing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!