[R] R minimal calculation error

Petr Savicky savicky at cs.cas.cz
Fri Aug 24 15:59:13 CEST 2012


On Fri, Aug 24, 2012 at 12:48:54PM +0200, Frederik Bertling wrote:
> Hi,
> 
> I'm doing some easy calculations to normalize some values. This looks like
> this:
> 
> x=mean(a+b+c+d ...)
> a=a-x
> b=b-x
> c=c-x
> d=d-x
> ...
> mean(a+b+c+d ...) ---> Should now be 0!
> However, I'm getting results like -2.315223e-18
> This is really near to 0 but not very aesthetic.
> 
> Can I prevent this? Or is this behaviour desired?

Hi.

This is a consequence of the limited precision, which is used
for speed. Examples of this type exist also for the decimal
arithmetic. Using 3 digit precision, the arithmetic mean of
the three numbers 1.02, 1.01, 1.01 is 1.01. So, the sum of the
differences

  1.02 - 1.01
  1.01 - 1.01
  1.01 - 1.01

is not zero.

See functions zapsmall(), all.equal().

Hope this helps.

Petr Savicky.




More information about the R-help mailing list