While loop to estime pi
Show older comments
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 Comments
S. Walter
on 3 Nov 2020
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
on 3 Nov 2020
While using the variable pi to contain the result is a bad idea in general, it is not the problem.
Answers (1)
John D'Errico
on 3 Nov 2020
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.
Categories
Find more on Parallel Computing 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!