Why does using modulo on non-integer values lose floating-point precision? [duplicate]

本小妞迷上赌 提交于 2019-12-20 04:34:23

问题


I am wondering why I am losing precision when using this code :

double x = 12.0456;    // or float : same result
System.out.println(x); // outputs 12.0456 obviously
x %= 1;                // should now be equal to 0.0456 right?
System.out.println(x); // outputs 0.04560000000000031 or 0.045599937 when using float

12.0456 modulo 1 should equal 0.0456 right? But it shows a slightly different value, why do I keep losing precision? I mean the code should substract exactly 1 until the value is less than 1.

However, I found out a way to get the correct value :

double x = 12.0456;
System.out.println(x);
x %= 1;
System.out.println((float)x); //outputs 0.0456 exactly

This way works perfectly, but do you guys have a better solution?

I don't care which floating point type I should use, I just want to find a clean way to get the correct value! I don't like having to convert the value to a double and then to a float.


回答1:


Float and double are imprecise - they have a finite amount of bits to represent a value.

Because humans use base 10, and computers use base 2, numbers that appear "simple" to us can be impossible to represent accurately as a float/double, especially the results of computations due to way CPUs execute them.



来源:https://stackoverflow.com/questions/14792253/why-does-using-modulo-on-non-integer-values-lose-floating-point-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!