Please look at following two code:
public static void main(String... args)
{
System.out.println(0.5==0.5f);
}
Output : true
public static void main(String... args)
{
System.out.println(0.1==0.1f);
}
Output: false
Why is it happening so?
In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers. In the above example, we can see the inaccuracy in comparing two floating-point numbers using “==” operator.
Equal Operator == The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns true value if both of the values are same (It compares only value of variable, not data types) and return a false value if both of the values are not same.
You are comparing two types of values: double and float. Think about the limitations of size with inexact numbers.
An example:
Exact values (decimal)
value1
-> 1/2 with 5 decimals is 0.50000value2
-> 1/2 with 10 decimals is 0.5000000000
then
value1 == value2
-> returns true
Inexact values (decimal)
value3
-> 1/3 with 5 decimals is 0.33333value4
-> 1/3 with 10 decimals is 0.3333333333
then
value3 == value4
-> returns false because they aren't the same.
0.1 cannot be represent exactly in binary (like 1/3 in decimal) but 0.5 can be.
The binary representation of 0.1d
-> 0.000(1100)1100110011...
The binary representation of 0.5d
-> 0.1
This has to do with the fact that floating point numbers are represented in the form c*2^q
. 0.5
can be represented as 1*2^-1
while 0.1
is impossible to represent accurately independent of how large you make c and q.
When comparing a float to a double, the float is cast to a double. If the number that is represented is already correctly representable as a float, it will have the same value when cast as a double, but if not, the double will have some extra significant digits and hence will compare non equal.
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