On the JVM, does division between two double values always yield the same exact result as doing the integer division?
With the following prerequisites:
x
and y
actually hold integer values.E.g. in the following code
double x = ...;
int resultInt = ...;
double y = x * resultInt;
double resultDouble = y / x; // double division
does resultDouble
always equal resultInt
or could there be some loss of precision?
There are two reasons that assigning an int to a double or a float might lose precision:
So it depeands on how big the int is, but in Java a double uses a 52 bit mantissa, so will be able to represent a 32bit integer without lost of data.
The are fabolous examples in this two sites:
1- Java's Floating-Point (Im)Precision
2- About Primitive Data Types In Java
also check:
Loss of precision - int -> float or double
Yes, if x
and y
are both in the int
range, unless the division is -2147483648.0 / -1.0
. In that case, the double result will match the result of integer division, but not int
division.
If both division inputs are in int
range, they are both exactly representable as double
. If their ratio is an integer and the division is not -2147483648.0 / -1.0
the ratio is in the int
range, and so exactly representable as double
. That double
is the closest value to the result of the division, and therefore must be the result of the double
division.
This reasoning does not necessarily apply if x
and y
are integers outside the int
range.
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