Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing float/double values using == operator

The code review tool I use complains with the below when I start comparing two float values using equality operator. What is the correct way and how to do it? Is there a helper function (commons-*) out there which I can reuse?

Description

Cannot compare floating-point values using the equals (==) operator

Explanation

Comparing floating-point values by using either the equality (==) or inequality (!=) operators is not always accurate because of rounding errors.

Recommendation

Compare the two float values to see if they are close in value.

float a;
float b;

if(a==b)
{
..
}
like image 317
Aravind Yarram Avatar asked Jul 26 '11 21:07

Aravind Yarram


People also ask

Can we use == to compare two float values?

Yes if they are Float objects.

Can we use == to compare two float or double numbers?

Some tips while using float and double in Java If you have to check conditions involving float and double values then instead of using == always use relational operator e.g. < or > for comparing floating-point numbers in Java.

Can you use == to compare doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

Does == work for floats?

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.


2 Answers

IBM has a recommendation for comparing two floats, using division rather than subtraction - this makes it easier to select an epsilon that works for all ranges of input.

if (abs(a/b - 1) < epsilon)

As for the value of epsilon, I would use 5.96e-08 as given in this Wikipedia table, or perhaps 2x that value.

like image 99
Mark Ransom Avatar answered Sep 21 '22 02:09

Mark Ransom


It wants you to compare them to within the amount of accuracy you need. For example if you require that the first 4 decimal digits of your floats are equal, then you would use:

if(-0.00001 <= a-b && a-b <= 0.00001)
{
..
}

Or:

if(Math.abs(a-b) < 0.00001){ ... }

Where you add the desired precision to the difference of the two numbers and compare it to twice the desired precision.

Whatever you think is more readable. I prefer the first one myself as it clearly shows the precision you are allowing on both sides.

a = 5.43421 and b = 5.434205 will pass the comparison

like image 34
Paul Avatar answered Sep 21 '22 02:09

Paul