5

On the JVM, does division between two double values always yield the same exact result as doing the integer division?

With the following prerequisites:

  • Division without remainder
  • No division by zero
  • Both 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?

Chris
  • 2,057
  • 2
  • 16
  • 20

3 Answers3

4

There are two reasons that assigning an int to a double or a float might lose precision:

  • There are certain numbers that just can't be represented as a double/float, so they end up approximated
  • Large integer numbers may contain too much precision in the lease-significant digits

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

Community
  • 1
  • 1
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
3

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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
3

The statement is true with the exception of Integer.MIN_VALUE, where the result of division of two integers may fall out of integer range.

    int n = Integer.MIN_VALUE;
    int m = -1;
    System.out.println(n / m);                          // -2147483648
    System.out.println((int) ((double)n / (double)m));  // 2147483647
apangin
  • 92,924
  • 10
  • 193
  • 247