Bug with rem() function
4 views (last 30 days)
Show older comments
rem(4.1*100,10) displays 10.00 which is wrong. rem(410,10) gives the right answer. rem(8.2*100,10) displays 10.00 which is wrong again.
Why is this happening? How do I solve this? This happens with almost all versions of Matlab..
4 Comments
KL
on 6 Dec 2017
John D'Errico
on 6 Dec 2017
Edited: John D'Errico
on 6 Dec 2017
It happens because you don't understand floating point arithmetic. It is not a bug, just a fact of life. For example, 4.1 is not in fact, stored as the decimal 4.1.
sprintf('%0.55f',4.1)
ans =
'4.0999999999999996447286321199499070644378662109375000000'
Doubles are stored in a IEEE binary form, which cannot exactly represent most decimal numbers. This is true of most computing languages.
Until you learn this fact and reformulate how you are trying to solve this problem you will continue to have the same random problem.
Answers (2)
Jan
on 6 Dec 2017
Edited: Jan
on 6 Dec 2017
rem(4.1*100,10) displays 10.00
Correct, it displays 10.00. But check the result more precisely:
rem(4.1 * 100, 10) - 10
4.1 * 100 - 410
What do you see? There is a rounding effect, which is expected for using floating point numbers. See the link posted by KL.
This does not only happen with all (not "almost all") versions of Matlab, but with other programming languages also. It is an effect of storing floating point values with a limited precision in binary format according to the IEEE754 standard. Even the processor uses this standard for doubles. There is no general method to "solve" this, because it is not a "problem". Maybe in your case you want this:
rem(round(4.1 * 100), 10) - 10
But for other problems, such a rounding might conceal important details.
Finally I can say it another time (you are not the first person today):
Welcome to the world of numerical maths with limited precision.
I did not really count it, but it is likely that this is the 100th time I have answered this question. Others have posted further 1000 of answers in the last years. Therefore you find it in the list of "frequently asked questions": http://matlab.wikia.com/wiki/FAQ It is worth to read the rest also - it is very efficient to profit from the mistakes made by others before.
0 Comments
Image Analyst
on 6 Dec 2017
If you want to treat them like they're integers, then cast them to integer.
result = rem(int32(4.1*100), 10)
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!