Comparing double values

July 20th, 2007
Even the experienced programmers often fall in a common mistake when it comes to double value comparison, which is using the equality operator == to compare two double precision (or float) values.

In order to represent a floating point number, a computer uses a finite number of bits. But there are certain numbers that require a bigger -even infinite- number of bits to be represented. In such cases the best the computer can do is to store the closest approximation.

The == equality operator performs a bit-to-bit comparison of the two values. This is fine when comparing integer values, but could be error prone in case of floating point numbers. It is possible, especially after a big number of floating point computations, two values that in theory would be considered equal, to end up being slightly different due to round ups. But even the slightest difference in the less important bits of the two numbers will make the equality operator to return false.

To compare two double values the proper way, you first have to choose a threshold value that defines the level of accuracy. This is how close two numbers should approach to be considered equal. Having this threshold value defined, to compare two double numbers you have to subtract them and see whether the absolute value of the difference is less than the threshold. Here is some some sample Java code:

if (Math.abs(d1-d2) < THRESHOLD) ...

The threshold value should be wisely chosen and depends on the level of accuracy that your application requires. For example, if you are working with decimal numbers of 4 significant digits after the decimal point, a good choice for the threshold value would be 0.00005. The rule is to take in account the numbers you are working with, and identify the smallest difference that two numbers should have to be considered not equal. Then you take this tiny value and cut it exactly in half, and that will be your threshold value.

Leave a Reply