Bug with rem() function

조회 수: 16 (최근 30일)
vimal A R
vimal A R 2017년 12월 6일
편집: Jan 2017년 12월 6일
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
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
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.

Image Analyst
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)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by