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?
Convert Int to Double – Widening Casting Int is a smaller datatype and double is a larger datatype. So, when you assign an int value to double variable, the conversion of int to double automatically happens in Java. This is also called widening casting.
A double is a 64 bit IEEE 754 floating-point. Double can provide precision up to 15 to 16 decimal points.
We can convert int value to Double object by instantiating Double class or calling Double. valueOf() method.
double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With