[R] Numbers that look equal, should be equal, but if() doesn't see as equal (repost with code included)
Prof Brian Ripley
ripley at stats.ox.ac.uk
Wed May 28 16:59:45 CEST 2003
On Wed, 28 May 2003, Paul Lemmens wrote:
> Hoi Thomas,
>
> --On woensdag 28 mei 2003 7:16 -0700 Thomas Lumley
> <tlumley at u.washington.edu> wrote:
>
> > On Wed, 28 May 2003, Paul Lemmens wrote:
> >
> >> Hi!
> >>
> >> Apologies for sending the mail without any code. Apparently somewhere
> >> along the way the .R attachments got filtered out. I have included the
> >> code below as clean as possible. My original mail is below the code.
> >
> > I still think you need not to be using ==. You want something like
> >
> > if ( abs(mean.b-mean.orig)/(epsilon+abs(mean.orig) < epsilon){
> >
> > You are effectively using epsilon=0, but epsilon=10e-10 should be
> > adequate.
> >
> Based on all the hints and explanations I've changed the test to
> 'identical(all.equal(mean.b, mean.orig, tolerance=.Machine$double.eps),
> FALSE)'.
>
> I still need to look into the concept of finite precision, because I still
> don't grasp how sometimes (as an extreme example, probably) 0.25 != 1/4.
> That this will happen for a number with a lot of different decimals I can
> understand (by an accumulation of rounding errors).
How you you think 0.25 gets converted to an internal number? It might be
0 + 2/10 + 5/100, and 2/10 and 5/100 cannot be represented exactly in
binary arithmetic. (R uses the system's strtod routine, so how it is done
is system-dependent: on my systems it does end up with the same bit
pattern as 1/4.)
As a real example
> (0.1 + 0.2) == 0.3
[1] FALSE
since
> print(c(0.1 + 0.2, 0.3), digits=20)
[1] 0.30000000000000004 0.29999999999999999
yet
> print(c(0.1, 0.2, 0.3), digits=20)
[1] 0.1 0.2 0.3
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list