No result for while loop Statement

1 view (last 30 days)
Zhuoying Lin
Zhuoying Lin on 14 Nov 2017
Commented: Guillaume on 15 Nov 2017
Matlab remains busy running my script forever, what's wrong with my script?
n=1;
while abs(pi-sum(4./((2*(1:n)-1)*(-1).^(n+1))))>=0.001
n=n+1;
sum(4./((2*(1:n)-1)*(-1).^(n+1)));
end
fprintf('The approximation using Leibniz''s formula falls within 0,001 of pi when it equals to')
fprintf('%.5f with n equls %d\n\n',sum(4./((2*(1:n)-1)*(-1).^(n+1))),n)
end

Answers (1)

Guillaume
Guillaume on 14 Nov 2017
Well, if you hadn't put a semicolon at the end of the line sum(...); effectively making it useless by suppressing the output, you would have seen that as n increases your sum gets further and further away from π instead of converging towards it.
That would be because you've implemented the formula incorrectly, in particular the (-1).^(n+1) which should be a vector. Manually testing each term of your formula for a few values of n should have shown you that.
Also note that you're recalculating all the terms of the expression each time you increase n, so your algorithm is not going to be particularly fast. I suppose it doesn't matter as it would converge quickly if the formula had been implemented right.
  7 Comments
Zhuoying Lin
Zhuoying Lin on 14 Nov 2017
so is there any reason why I get this result?
Guillaume
Guillaume on 15 Nov 2017
You need at least 500 terms (i.e n=1000) to get within ±0.001 of pi.
For n = 1000, the value is indeed ~3.14059265383979, which is ~0.000999999749998981 less than π, so within 0.001 of π.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!