Failure in a simple division

15 views (last 30 days)
Gino Massafra
Gino Massafra on 12 Nov 2015
Commented: Star Strider on 6 Jan 2020
Hi everybody, I found a litle bug in a code of mine related to a failure in a simple division: >> 473/10 ans = 47.299999999999997 >> why does this happen? Have I done something to wrong in preferences or setting option? How to fix it? Help me please

Accepted Answer

Star Strider
Star Strider on 12 Nov 2015
Not a bug at all. It’s ‘floating point approximation error’. Representing decimal numbers — including integers — in binary is somewhat analogous to representing the fraction 1/3 in decimal: 0.3333.... No matter how long the sequence, it will never equal 1/3.
  11 Comments
Stephen23
Stephen23 on 6 Jan 2020
Edited: Stephen23 on 6 Jan 2020
"I ran into the same issue and this answer seems to me to be incomplete."
Nope, the answer is still quite correct. All of your values happen to resolve to exactly the same floating point number (and there is nothing unusual about that, it certainly can happen, although should definitely not be relied upon):
>> test = str2double('9.7');
>> num2strexact(test)
ans =
9.699999999999999289457264239899814128875732421875
>> test = (test*10)/10;
>> num2strexact(test)
ans =
9.699999999999999289457264239899814128875732421875
>> num2strexact(9.7)
ans =
9.699999999999999289457264239899814128875732421875
"something has changed in how Matlab is presenting the numbers"
I very much doubt that. Do you have any supporting examples?
"...so at the least there is a failure of reversability"
As operations on floating point numbers are neither commutative nor associative, I don't see how you can describe their documented behavior as a "failure".
"So why did the poster run into a problem originally?"
What problem? The original question just showed a double floating point value displayed correctly according to MATLAB's format documentation:
>> 473/10
ans =
47.299999999999997
>> num2strexact(473/10)
ans =
4.72999999999999971578290569595992565155029296875e1
I just tried it on three MATLAB versions and it looks exactly the same on each of them. Not only that, but the original question did not mention any logical equivalency operation, so it is not clear what you think their "problem" was, or how it relates to your comment and examples.
"Is there some case where Matlab should also have taken it into account and did not?"
I very much doubt that. Do you have any supporting examples?
So far everything in your comment and in the original question are explained perfectly by the well-documented behavior of binary floating point numbers. Nothing seems to have changed.
Star Strider
Star Strider on 6 Jan 2020
@Stephen — Thank you!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!