Bug with rem() function
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
John D'Errico
2017-12-6
编辑:John D'Errico
2017-12-6
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.
回答(2 个)
Jan
2017-12-6
编辑:Jan
2017-12-6
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 个评论
Image Analyst
2017-12-6
If you want to treat them like they're integers, then cast them to integer.
result = rem(int32(4.1*100), 10)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!