Given two double
values, p
and q
, how can I determine if their quotient:
double result = p / q;
is an exact result in terms of the binary values of p
and q
?
That is, whether result
is exactly equal to the mathematical division of p
and q
.
Clearly this is true for some values, such as 1.0 / 2.0
and false for others such as 1.0 / 5.0
, so I'm looking for an idiomatic and accurate way to separate the cases.
It seems like the floating point modulus p % q == 0
might work, but I'm not sure!
You could use BigDecimal
to see if the division is exact:
private static boolean canDivideExact(double p, double q) {
double r = p / q;
BigDecimal d = new BigDecimal(r);
return d.multiply(new BigDecimal(q)).compareTo(new BigDecimal(p)) == 0;
}
For example:
System.out.println(canDivideExact(1, 2)); //true
System.out.println(canDivideExact(1, 3)); //false