[R] Best way to compute a sum
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))
 1 2 4 3
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
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
Size: 836 bytes
Desc: not available
More information about the R-help