Bug with rem() function

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

"which is wrong again."
Nope, it is not wrong. It is correct to the precision of the floating point numbers that you are using.
I need the remainder when 4.1*100 is divided by 10. What function should I use?
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.

Sign in to comment.

Answers (2)

Jan
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.
If you want to treat them like they're integers, then cast them to integer.
result = rem(int32(4.1*100), 10)

Categories

Asked:

on 6 Dec 2017

Edited:

Jan
on 6 Dec 2017

Community Treasure Hunt

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

Start Hunting!