while loop doesn't produce correct result

10 ビュー (過去 30 日間)
Jimmy W
Jimmy W 2017 年 4 月 12 日
コメント済み: James Tursa 2017 年 4 月 12 日
sum = 0;
n = 0;
C = (2/(pi*(1-4*n^2)))^2;
while sum < (1/2)*0.99
n = n+1;
sum = sum + C;
end
disp(['number of terms:',num2str(n),'sum',num2str(sum)])
These are my codes. I want matlab to keep calculating until sum is greater than 99% of a half. However it stops at the first calculation and the result is clearly wrong. Any help would be greatly appreciated! Thanks!

採用された回答

Roger Stafford
Roger Stafford 2017 年 4 月 12 日
You have not placed the line "C = (2/(pi*(1-4*n^2)))^2;" inside the 'while' loop where it could be updated with changing values of 'n', so 'C' stays constant. That will produce erroneous computation for you.
  2 件のコメント
Jimmy W
Jimmy W 2017 年 4 月 12 日
If I put the C line in the loop, it never stops calculating. The equation is always positive so at some point the sum should reach the target value. Is there anything else that I have done wrong?
James Tursa
James Tursa 2017 年 4 月 12 日
C get small rather quickly, so the sum never even gets close to 1/2.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by