Why is arbitrary precision in double literals allowed in Java?

人走茶凉 提交于 2019-12-04 06:09:23

The problem is that very few decimals that you might type can be represented exactly as an IEEE float. So if you removed all non-exact constants you would make using double literals very unwieldy. Most of the time the behaviour of "pretend we can represent it" is far more useful.

The main reason is probably that Java simply can't tell when you're running out of precision because there is no CPU op code for that.

Why is there no CPU flag or similar? Because the representation of the number simply doesn't allow it. For example even simple numbers like "0.1" have no definite representation. 0.1 gives you "00111111 10111001 10011001 10011001 10011001 10011001 10011001 10011010" (see http://www.binaryconvert.com/result_double.html?decimal=048046049).

That value isn't precisely 0.1 but 1.00000000000000005551115123126E-1.

So even for these "simple" cases, the code would have to throw an exception.

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