Addition of very small Double values (Java) [duplicate]

*爱你&永不变心* 提交于 2020-01-03 05:06:01

问题


I was wondering, why my simple addition of some double values leads to the following results in Java:

double a = 1 + 1E-10; // 1.0000000001 (as expected)
double b = 1 + 1E-15; // 1.000000000000001 (as expected)
double c = 1 + 1E-20; // 1.0 (why?)

I thought I can at least add a value of Double.MIN_VALUE, which seems to be 4.9E-324.

What am I doing wrong here?


回答1:


As @Turing85 points out, a double has 11 bits of exponent and 53 bits of mantissa.

What we are calculating here is 1.0 + 1E-20. To represent that number (more precisely than 1.0) we need at least 21 decimal digits of precision or 71 bits. That is more precision than a double provides in the mantissa.

So, the nearest representable double number to 1.0 + 1E-20 is .... 1.0. And that's the result you get.

Welcome to mysterious world of floating point arithmetic.




回答2:


You are not doing anything wrong here. The concept of decimal precision is at hand. There is always a possibility of error in floating point numbers. And the common error value is represented as:

- 1/2E-n <= error <=  1/2E-n

where n is the number of decimal digits you have defined.

More about floating point errors can be found here.



来源:https://stackoverflow.com/questions/43542063/addition-of-very-small-double-values-java

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