Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0.5==0.5f is true but 0.1==0.1f is false? [duplicate]

Tags:

java

literals

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?

like image 911
Anurag Shukla Avatar asked Jul 11 '15 12:07

Anurag Shukla


People also ask

Why is it not correct to compare floating points numbers for equality using == like integers are?

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.

Can we equate double variables 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.


2 Answers

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.50000
value2 -> 1/2 with 10 decimals is 0.5000000000

then

value1 == value2 -> returns true

Inexact values (decimal)

value3 -> 1/3 with 5 decimals is 0.33333
value4 -> 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

like image 60
David Pérez Cabrera Avatar answered Oct 17 '22 11:10

David Pérez Cabrera


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.

like image 20
Voo Avatar answered Oct 17 '22 12:10

Voo