Is double division equal to integer division if there is no remainder?

In the JVM, does the separation between two double values ​​always give the exact same result as the whole division?

With the following prerequisites:

  • Department without a trace
  • No division by zero
  • Both xand yreally contain integers.

eg. in the following code

double x = ...;
int resultInt = ...;
double y = x * resultInt;
double resultDouble = y / x; // double division

is it resultDoublealways equal resultIntor may there be some loss of accuracy?

+4
source share
3 answers

, x y int, -2147483648.0 / -1.0. , int .

int, double. , -2147483648.0 / -1.0, int double. double double.

, x y int.

+3

, int :

  • , double/float,
  • .

, , int, Java double 52- , 32- .

:

1- (Im)

2- Java

:

- int → float double

+4

The statement is true, except Integer.MIN_VALUEwhere the result of dividing two integers can fall out of the 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
+3
source

Source: https://habr.com/ru/post/1677267/


All Articles