[R] problem with sum function

Petr Savicky savicky at cs.cas.cz
Thu Mar 1 23:02:53 CET 2012


On Thu, Mar 01, 2012 at 01:49:44PM -0800, Mark A. Albins wrote:
> Hi!
> 
> I'm running R version 2.13.0 (2011-04-13)
> Platform: i386-pc-mingw32/i386 (32-bit)
> 
> When i type in the command:
> 
> sum(c(-0.2, 0.8, 0.8, -3.2, 1.8))
> 
> R returns the value:
> 
> -5.551115e-17
> 
> Why doesn't R return zero in this case?  There shouldn't be any rounding 
> error in a simple sum.

Hi.

There is a rounding error, since numerical values are represented
in binary system and, for example, 0.2 = 1/5 cannot be represented
in binary exactly. A simpler version is

  0.1 + 0.2 - 0.3

  [1] 5.551115e-17

Use round(), for example

  round(sum(c(-0.2, 0.8, 0.8, -3.2, 1.8)), digits=7)

  [1] 0

See FAQ 7.31 and/or 

  http://rwiki.sciviews.org/doku.php?id=misc:r_accuracy

for further hints.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list