[R] Numbers that look equal, should be equal, but if() doesn't see as equal

Thomas Lumley tlumley at u.washington.edu
Tue May 27 16:20:24 CEST 2003

On Tue, 27 May 2003, Paul Lemmens wrote:
> Problem description: if one calculates the bins or bin means by hand, the
> mean of the bin means is visually the same as the overall mean, even with
> options(digits=20), but *still* the test fails.

It is possible at least on some systems for numbers to print the same but
not be ==.  It's very difficult to ensure that two different floating
point numbers are ==, so it is almost always better to check that the
difference is small, which is what all.equal() does.

To get floating point equality you need not just mathematical equivalence
but quite a lot of care in handling rounding -- and it can still be broken
quite easily by optimising compilers.  If you look at the R tests
directory you will see quite a lot of places where mathematically
identical quantities are compared with relatively wide tolerances for
exactly this reason.

Usually getting within 10^-10 or so is sufficient and easily achievable.


More information about the R-help mailing list