Hacker Newsnew | comments | show | ask | jobs | submit login

wait. why is that false? both come out to 0.1, which should be equal?



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...).

-----




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: