Java precision during division and multiplication alterneting process [duplicate]

左心房为你撑大大i 提交于 2019-12-13 22:03:55

问题


Possible Duplicate:
How to resolve a Java Rounding Double issue

Please Help, I programm some calculator in Java. I use double type. Double has 15 digits after the decimal point. I have problem with the following:

1/3 * 3 = 0.9999999999999999

I need 1/3 * 3 = 1

How can I solve this problem? I keep result in Double. The same problem I have with other mathematical operations, for example

sqrt(6) = 2.449489742783, and next I square the result and I get: 5.999999999999999


回答1:


You're dealing with inherent limitations of floating-point arithmetic.

  • Read the paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.
  • For equality-checking, you should be using something like abs(x-y) < epsilon rather than x == y
  • For display purposes, you should round to the nearest decimal place that you actually care about.



回答2:


Certain numbers cannot be represented exactly in binary floating point. 1/3 is one of them. See http://en.wikipedia.org/wiki/Floating_point For that matter, 1/3 cannot be represented exactly in decimal either.

Your calculator should use a java.text.NumberFormat to present the numbers.




回答3:


The reason why you are seeing this is due to the computers inability to understand infinity.

A computer has limitations, so it does not understand the fact that 1/3 is never-ending. This causes it to round. This can be solved as Jason S posted above. Using these special class, people have started to program ways to computer whether or not something goes to infinity, then attempt to deal with it.



来源:https://stackoverflow.com/questions/8404575/java-precision-during-division-and-multiplication-alterneting-process

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