Why two equal numbers are not equal?

20 ビュー (過去 30 日間)
Florian Neveu
Florian Neveu 2016 年 12 月 14 日
編集済み: James Tursa 2016 年 12 月 14 日
Hello everyone,
I had some difficulties comparing some numbers and the problem is simply summarized below :
So can someone tell me why and how this can happen? And how to avoid this kind of problem in the future if possible.
Thank you.

採用された回答

Adam
Adam 2016 年 12 月 14 日
You should never test equality between floating point numbers. There are any number of places you could search online to see the reasons for this. Many floating point numbers can not be represented to 100% accuracy and maths done on them will often introduce small inaccuracies so you should always test equality within a tolerance, not directly. The difference may only be 1e-16 and so basically equivalent to 0 for all sensible usage, but it will still fail an == test.

その他の回答 (2 件)

James Tursa
James Tursa 2016 年 12 月 14 日
編集済み: James Tursa 2016 年 12 月 14 日
Already answered by others, but here is a detailed decimal conversion of what is going on with your particular example:
>> num2strexact(0.65)
ans =
0.65000000000000002220446049250313080847263336181640625
>> num2strexact(0.05)
ans =
5.000000000000000277555756156289135105907917022705078125e-2
>> num2strexact(0.05*17)
ans =
0.850000000000000088817841970012523233890533447265625
>> num2strexact(0.65+0.05*17)
ans =
1.5
>>
>> num2strexact(0.3)
ans =
0.299999999999999988897769753748434595763683319091796875
>> num2strexact(0.05)
ans =
5.000000000000000277555756156289135105907917022705078125e-2
>> num2strexact(0.05*24)
ans =
1.20000000000000017763568394002504646778106689453125
>> num2strexact(0.3+0.05*24)
ans =
1.5000000000000002220446049250313080847263336181640625
So, you got lucky in one case and unlucky in the other case. You can find num2strexact on the FEX here:

michio
michio 2016 年 12 月 14 日
Also please refer to "Compare Floating-Point Numbers" example of the doc page: Determine equality.
It's usually recommended to compare floating-point numbers using a tolerance, tol, instead of using ==.
  1 件のコメント
Steven Lord
Steven Lord 2016 年 12 月 14 日

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by