Java precision during division and multiplication

2019-09-20 16:13发布

问题:

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.