Comparing floating point numbers - a word of caution and a solution
Archive - Originally posted on "The Horse's Mouth" - 2010-02-01 22:56:38 - Graham Ellis
"Think of a number between 5 and 15.
Double it.
Add fourteen.
Halve it.
Take away the number you first thought of.
Is the result 7?"
We all played games like that as children, thinking of the number 0 ourselves so that we could do an easy calculation and impress our friends. And the result was 7 ... whether you started from 0, 5, 7, 9, 13, 15 ... or any other value.
But if you try such things with floating point numbers in more or less any programming language, you'll not necessarily find that you get back to an exact number, or the number you first thought of. And that's because computers store floating point numbers in a format where they are ever so slighly rounded.
The issue is a common one to most languages, but it happened to come up today on a Ruby course, so I've written an example in Ruby to show the problem. I took a number, divided it, added, multiplied, subtracted, and tested to see if I was back where I started. It wasn't - 1.0 had become 0.999999999999993 and When I tested the result to see if it was equal to one, my program declared that it was NOT!
Be careful when testing floating point numbers in any language - you'll do far better to work with integers much / most of the time. And if you must test a floating point variable on which you have done significant calculations for equality, you'll be well advised to do so by checking to see how much the absolute difference between the two values is, as a proportion of one of the values that you're comparing. Does this sound complex? It isn't, and it can easily be implements as a function: