Skip to content

Comparison of Double Constants

I researched this a lot and I know something about precision errors in the doubles; however I couldnt find the answer. My question is: is it always safe to compare double constants? What do I mean by that is, just reading the double from a string or creating in the source code. No operation (adding, subtracting etc.) will be done on them. If I create a variable like

double c = 3.0.

Will the following equation will always be true? c==3.0000.

For example is there any possibility to see wrong evaluation of an equation like this 1.23456789 < 1.23456788?

Answer

It’s always safe; with one caveat.

Here’s an example:

1.232342134214321412421 == 1.232342134214321412422

That is true; all double constants are silently rounded to the nearest representable double, and for both of these numbers, it is the same double.

Thus, given 2 actual mathematical numbers A and B where A < B, then if you turn those numbers into double literals and run these 3 expressions on it, you get the following scenarios:

If A and B are rounded to different doubles, you get guarantees:

  • A < B will be true
  • A == B will be false
  • A > B will be false

If A and B are really close to each other, they may round to the same double, and you get:

  • A < B will be false
  • A == B will be true
  • A > B will be false

In other words, ‘less than’ and ‘greater than’ can be bent into being equal, but a lesser number will never be erroneously treated as larger.