In Java, is multiplying a double by 0.0000001 the same as dividing it by 10000000? My intuition is that there could be a difference because 0.0000001 cannot be represented exactly in a double.
Is multiplying by 0.0000001 the same as dividing by 10000000?
Asked Answered
No it's not the same for the reason you mentioned. Here's an example:
double x = 894913.3;
System.out.println(x * 0.0000001); // prints 0.08949133
System.out.println(x / 10000000); // prints 0.08949133000000001
Using a BigDecimal
, we can see the difference between the two values:
System.out.println(new BigDecimal(0.0000001));
System.out.println(new BigDecimal((double)10000000));
Ouput:
9.99999999999999954748111825886258685613938723690807819366455078125E-8
10000000
Ok, so where is the explanation? –
Linehan
@BorisTreukhov In the question. :) –
Berman
The intuition in the question is the correct explanation. The closest double to 0.0000001 is 9.99999999999999954748111825886258685613938723690807819366455078125E-8. –
Conventionality
It's not only not the same because of the double representation but also if you multiply an integer by a double the result is a double. If you devide an integer by an integer, the result is an integer:
int i = 1;
System.out.println(i*0.0000001);
System.out.println(i/10000000);
prints
1.0E-7
0
The question asked about multiplying a double or dividing "it", I assume the same double. –
Conventionality
Oops, you are correct. Should I keep my answer anyways or remove it? –
Tsan
© 2022 - 2024 — McMap. All rights reserved.