Failure in a simple division
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Gino Massafra
el 12 de Nov. de 2015
Comentada: Star Strider
el 6 de En. de 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
0 comentarios
Respuesta aceptada
Star Strider
el 12 de Nov. de 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 comentarios
Stephen23
el 6 de En. de 2020
Editada: Stephen23
el 6 de En. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!