Reputation: 3205
I have read this - Why Are Floating Point Numbers Inaccurate?
So, sometimes precision can be changed in floating point number because of its representation style (scientific notation with an exponent and a mantissa).
But if I cast an integer value to double, is there any chance to change the precision of double slightly in Java?
I mean,
int i = 3;
double d = (double) i;
System.out.println(d);
the output I got 3.0
as I expected.
but, is there any chance of being precision changed like 3.000001
because of representation style of double in Java?
Upvotes: 25
Views: 2918
Reputation: 54223
You can iterate over i
until you find a 2**i
double which is equal to 2**i + 1
:
import java.util.stream.IntStream;
public class PrecisionLoss
{
public static void main(String[] args) {
double epsilon = 1;
Integer maxInt = IntStream.iterate(0, i -> i + 1)
.filter(i -> Math.pow(2, i) == Math.pow(2, i) + epsilon)
.findFirst().getAsInt();
System.out.println("Loss of precision is greater than " + epsilon
+ " for 2**" + maxInt + " when using double.");
}
}
It outputs:
Loss of precision is greater than 1.0 for 2**53 when using double.
Which confirms the accepted answer.
Note that in Javascript, there is no integer type and doubles are used instead (they are called Number
s). If they are large enough, consecutive Number
s can be equal to each other.
Upvotes: 5
Reputation: 140319
Not for int to double, but you might for long to double (or int to float):
2^53-1
(or less than -2^53
) can be represented exactly by a double;2^24-1
(or less than -2^24
) can be represented exactly by a float.This restriction comes about because of the number of bits used to represent the mantissa (53 in doubles, 24 in floats).
Upvotes: 33