[R] cumsum vs. sum

2009-02-17 Thread Stavros Macrakis
I recently traced a bug of mine to the fact that cumsum(s)[length(s)] is not always exactly equal to sum(s). For example, x<-1/(12:14) sum(x) - cumsum(x)[3] => 2.8e-17 Floating-point addition is of course not exact, and in particular is not associative, so there are various possible r

Re: [R] cumsum vs. sum

2009-02-17 Thread Gabor Grothendieck
Check out sum.exact and cumsum.exact in the caTools package. > library(caTools) Loading required package: bitops > x <- 1/(12:14) > sum(x) - cumsum(x)[3] [1] 2.775558e-17 > sum.exact(x) - cumsum.exact(x)[3] [1] 0 On Tue, Feb 17, 2009 at 5:12 PM, Stavros Macrakis wrote: > I recently traced a bug

Re: [R] cumsum vs. sum

2009-02-18 Thread Martin Maechler
> "GaGr" == Gabor Grothendieck > on Tue, 17 Feb 2009 20:53:18 -0500 writes: GaGr> Check out sum.exact and cumsum.exact in the caTools package. >> library(caTools) GaGr> Loading required package: bitops >> x <- 1/(12:14) >> sum(x) - cumsum(x)[3] GaGr> [1] 2.7755

Re: [R] cumsum vs. sum

2009-02-18 Thread Martin Maechler
> "SM" == Stavros Macrakis > on Wed, 18 Feb 2009 10:00:40 -0500 writes: SM> Nice! Glad to hear it. It sounds as though it is still possible for SM> cumsum(x)[length(x)] to not be exactly equal to sum, though? Well, possible, probably yes, platform-dependently; However I vag

Re: [R] cumsum vs. sum

2009-02-18 Thread Stavros Macrakis
Hmm. Why not use the same method to guarantee the same result? Or at least document the possibility that cumsum(x)[length(x)] != sum(x)... that seems like an easy trap to fall into. -s On Wed, Feb 18, 2009 at 11:39 AM, Martin Maechler wrote: >> "SM" == Stavros Macrakis >>

Re: [R] cumsum vs. sum

2009-02-18 Thread Duncan Murdoch
On 18/02/2009 12:41 PM, Stavros Macrakis wrote: Hmm. Why not use the same method to guarantee the same result? Or at least document the possibility that cumsum(x)[length(x)] != sum(x)... that seems like an easy trap to fall into. Assuming equality of floating point numbers computed by two dif

Re: [R] cumsum vs. sum

2009-02-18 Thread Berwin A Turlach
G'day all, On Wed, 18 Feb 2009 12:41:27 -0500 Stavros Macrakis wrote: > Hmm. Why not use the same method to guarantee the same result? Hmm, I did not look at the source code but, potentially, sum() could use some tricks to reduce rounding errors further that would not be available to cumsum(

Re: [R] cumsum vs. sum

2009-02-18 Thread Stavros Macrakis
Duncan, Berwin, Martin, Thanks for your thoughtful explanations, which make perfect sense. May I simply suggest that the non-identity between last(cumsum) and sum might be worth mentioning in the cumsum doc page? -s __ R-help@r-project.org