Strange behavior of if statement

1 回表示 (過去 30 日間)
martino corrà
martino corrà 2021 年 4 月 15 日
コメント済み: martino corrà 2021 年 4 月 15 日
i have this very simple code that should return 'ans = 1' when run, since the sum of d is 1. However it returns the error message specified in the 'else' section instead, as if d didn't add up to 1. What's going on?
d = [.4 .1 .1 .1 .1 .1 .1];
if sum(d) == 1
sum(d)
else
error('d doesnt add up to 1')
end

採用された回答

Rik
Rik 2021 年 4 月 15 日
Welcome to floating point integers.
Matlab stores these numbers in a binary representation with a finite precision. Similar to what would happen if you only store 4 decimals and do this: (1/3)*3=0.3333*3=0.9999.
You should probably compare to a tolerance:
d = [.4 .1 .1 .1 .1 .1 .1];
if abs( sum(d)-1 ) <= 2*eps
sum(d)
else
error('d doesnt add up to 1')
end
ans = 1.0000
  1 件のコメント
martino corrà
martino corrà 2021 年 4 月 15 日
ah I see, thank you soo soo much, i've been trying to figure out what was going on for hours! It seemed like matlab was mocking me! now i understand. Thanks a lot!

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

その他の回答 (1 件)

DGM
DGM 2021 年 4 月 15 日
編集済み: DGM 2021 年 4 月 15 日
It's correct. The sum isn't 1. It's approximately 1.
d = [0.4 0.1 0.1 0.1 0.1 0.1 0.1]; % leading zeros for readability, pls
sum(d) % that sure looks like 1
sum(d)-1 % but you just don't have the display resolution to see the error
gives
ans =
1.0000
ans =
-1.1102e-16
Beware simple equality tests when using floating point numbers. Test to within a tolerance.
tol=1E-12;
if abs(sum(d)-1)<tol
sum(d)
else
error('d doesnt add up to 1')
end
  1 件のコメント
martino corrà
martino corrà 2021 年 4 月 15 日
Now i get it, thank you so much!!!

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

カテゴリ

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

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by