News for hackers. Stuff that matters.
Re:0.3 - 0.2 == 0.2 - 0.1 is falsy. Which language gets this... by Breakthrough on Saturday October 06, 2012 @07:58PM (#4622163)
In binary, you can't represent any of 0.1, 0.2, nor 0.3 with "proper" fractions, as they are irrational in a radix-2 number system. Thus, when actually performing the operation (0.3 - 0.2) - (0.2 - 0.1), the result may actually be non-zero, although very small.

The best thing to do here would be to use an inline comparison function with a threshold:

    inline bool is_equal(double a, double b, double threshold = 0.0000001f)
    {
        if ( abs(a-b) < threshold )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
Unfortunately, compounding floating point operations can drastically reduce calculation accuracy, leading to requiring a greater threshold value... Which is why I highly recommend reading the article titled "What Every Computer Scientist Should Know About Floating-Point Arithmetic" by David Goldberg (circa 1991, available at http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.ht...).

There are no comments on this comment yet.