Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 903
Chris Avatar asked Dec 23 '22 18:12

Chris


2 Answers

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

like image 176
A Monad is a Monoid Avatar answered Dec 26 '22 07:12

A Monad is a Monoid


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.

like image 35
Patricia Shanahan Avatar answered Dec 26 '22 06:12

Patricia Shanahan