[R] Best way to compute a sum

Lasse Kliemann lasse-list-r-help-2009 at mail.plastictree.net
Thu Jun 24 22:08:23 CEST 2010


  > a <- 0 ; for(i in (1:200000000)) a <- a + 1/i
  > b <- 0 ; for(i in (200000000:1)) b <- b + 1/i
  > c <- sum(1/(1:200000000))
  > d <- sum(1/(200000000:1))
  > order(c(a,b,c,d))
  [1] 1 2 4 3
  > b<c
  [1] TRUE
  > c==d
  [1] FALSE

I'd expected b being the largest, since we sum up the smallest 
numbers first. Instead, c is the largest, which is sum() applied 
to the vector ordered with largest numbers first.

Can anyone shed some light on this?

What is the best way in R to compute a sum while avoiding 
cancellation effects?

By the way, sum() in the above example is much faster than the 
loops, so it would be nice if we could utilize it.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20100624/76d2cffb/attachment.bin>


More information about the R-help mailing list