one problem about rounding issue (but not the round function)

6 ビュー (過去 30 日間)
Lin Yang
Lin Yang 2018 年 7 月 10 日
編集済み: Matt J 2018 年 7 月 10 日
Hi everyone, I encounter one problem in one part of my program. To simpilfy, it's:
A = 1.495:0.1:2.495;
for i = 1:11
disp(num2str(A(i),'%5.2f'));
end
it shows:
1.50
1.60
1.70
1.80
1.90
2.00
2.10
2.20
2.29
2.40
2.50
In a different machine it shows:
1.50
1.60
1.70
1.80
1.90
2.00
2.10
2.20
2.30
2.40
2.49
This may be due to "the round function rounds away from zero to the integer with larger magnitude" in this link's sentence: https://ww2.mathworks.cn/help/matlab/ref/round.html?lang=en But I'm not sure. could anyone help me solve this problem, to let the program stably display correct rounding result? Many thanks.

採用された回答

Matt J
Matt J 2018 年 7 月 10 日
編集済み: Matt J 2018 年 7 月 10 日
Because of floating point errors, the "2.2950" is really 2.294999999999999999999999999999999999999, which rounds to 2.29. Do instead
A = round( 1.495:0.1:2.495 ,2);
or
disp(num2str(round( A(i) ,2) ,'%5.2f'))

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by