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!