Why does this code, which is written to calculate sin(0) to sin(pi), also calculate sin(1.1*pi) even though the while loop should forbid it?
2 ビュー (過去 30 日間)
古いコメントを表示
clc; clear; i=1; x=0; y(i)=sin(x*pi); while x<1 i=i+1; x=x+0.1; y(i)=sin(x*pi); end y

0 件のコメント
回答 (2 件)
Steven Lord
2016 年 11 月 2 日
"Ten steps of length t [t = 0.1] are not precisely the same as one step of length 1. MATLAB is careful to arrange that the last element of the vector 0:0.1:1 is exactly equal to 1, but if you form this vector yourself by repeated additions of 0.1, you will miss hitting the final 1 exactly."
Alexandra Harkai
2016 年 11 月 2 日
Is there a specific reason why you want to use a while loop? This would be much easier/quicker/easier to read is you vectorise it:
y = sin(pi*(0:0.1:1))
2 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!