Wrong result as comparing two double numbers in Matlab 2016

5 views (last 30 days)
Hi guys,
I got wrong result as comparing two double number in Matlab 2016 as
>> x=0.3
x =
0.3000
>> x<0.2+0.1
ans =
1
I do not know why ??? anything is wrong here ?
Thanks TH
  1 Comment
Stephen23
Stephen23 on 3 Aug 2017
Edited: Stephen23 on 7 Sep 2017
"I got wrong result as comparing two double number..."
No, that result is correct. The reason is because all numbers in your computer are stored as finite binary numbers, and they cannot represent exactly those decimal fractions (in just the same way that you cannot write 1/3 exactly using finite decimal digits).
Your code tests for equivalence of floating point values, which is a very buggy and unreliable way to write code. You need to change your algorithm to take into account floating point error:
etc, etc, etc

Sign in to comment.

Answers (3)

Steven Lord
Steven Lord on 2 Aug 2017
This is NOT a bug. See this Answer.

John D'Errico
John D'Errico on 2 Aug 2017
Edited: John D'Errico on 2 Aug 2017
What is wrong is your appreciation of how numbers are stored in floating point arithmetic.
Doubles are stored in a binary format, NOT as decimals. So 0.3 is NOT stored as 0.3.
x=0.3
x =
0.3
It looks like 0.3. But is it?
sprintf('%0.55f',x)
ans =
'0.2999999999999999888977697537484345957636833190917968750'
Remember that most decimal fractions are not exactly representable in binary form, just like 1/3 is not representable exactly in a finite number of decimal digits.
y = 0.2 + 0.1 y = 0.3
Yep. That looks like 0.3 too. But is it?
sprintf('%0.55f',y)
ans =
'0.3000000000000000444089209850062616169452667236328125000'
In fact, the two numbers are off by one bit down in the least significant bits of the number.
sprintf('%bx',y)
ans =
'3fd3333333333334'
sprintf('%bx',x)
ans =
'3fd3333333333333'
NEVER compare two floating point doubles for exact equality. Well, there are some notable exceptions. So unless you know the exceptions, then assume never applies.

Thang Hoang
Thang Hoang on 3 Aug 2017
Thank you all,

Community Treasure Hunt

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

Start Hunting!