My coworker did this experiment:
public class DoubleDemo { public static void main(String[] args) { double a = 1.435; double b = 1.43; double c = a - b; System.out.println(c); } }
For this first-grade operation I expected this output:
0.005
But unexpectedly the output was:
0.0050000000000001155
Why does double fails in such a simple operation? And if double is not the datatype for this work, what should I use?
doubles are not exact. It is because there are infinite possible real numbers and only finite number of bits to represent these numbers.
Syntax : public static long subtractExact(long x, long y) Parameter : x : the first value y : the second value to be subtracted from the first Return : This method returns the difference of the arguments. Exception : It throws ArithmeticException - if the result overflows a long. Example :To show working of java.
Double-precision floating-point format (sometimes called FP64 or float64) is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.
double
is internally stored as a fraction in binary -- like 1/4 + 1/8 + 1/16 + ...
The value 0.005
-- or the value 1.435
-- cannot be stored as an exact fraction in binary, so double
cannot store the exact value 0.005
, and the subtracted value isn't quite exact.
If you care about precise decimal arithmetic, use BigDecimal
.
You may also find this article useful reading.
double and float are not exactly real numbers.
There are infinite number of real numbers in any range, but only finite number of bits to represent them! for this reason, rounding errors is expected for double and floats.
The number you get is the closest number possible that can be represented by double in floating point representation.
For more details, you might want to read this article [warning: might be high-level].
You might want to use BigDecimal
to get exactly a decimal number [but you will again encounter rounding errors when you try to get 1/3
].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With