No result for while loop Statement

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

답변 (1개)

Guillaume
Guillaume 2017년 11월 14일

0 개 추천

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

Zhuoying Lin
Zhuoying Lin 2017년 11월 14일
I write (-1).^(n+1) to design a sign for each nth term, so the result should be a number with +/- sign.
I repeat, manually testing each term of your formula for a few values of n should have shown you the problem.
Try
n = 4
4./((2*(1:n)-1)
(-1).^(n+1)
4./((2*(1:n)-1)*(-1).^(n+1)
You're multiplying all the elements of the whole vector [1, 1/3, 1/5, ...] by the scalar (-1).^(n+1)
You need to multiply the sequence by another vector [1, -1, 1, -1, ...], not a scalar.
Zhuoying Lin
Zhuoying Lin 2017년 11월 14일
Okay I see what you mean now, yes it works! Thank you!
Zhuoying Lin
Zhuoying Lin 2017년 11월 14일
However, I get n=1000 and the approximation is 3.140592654, this does not fall within 0.001 of pi though
Guillaume
Guillaume 2017년 11월 14일
Actually, I was wrong about one thing, the series does not converge quickly. According to wikipedia, "Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Calculating π to 10 correct decimal places using direct summation of the series requires about five billion terms"
Zhuoying Lin
Zhuoying Lin 2017년 11월 14일
so is there any reason why I get this result?
Guillaume
Guillaume 2017년 11월 15일
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 π.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2017년 11월 14일

댓글:

2017년 11월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by