Skip to content
Prev 42014 / 63435 Next

bug in sum() on integer vector

Hi Duncan,
On 11-12-09 11:39 AM, Duncan Murdoch wrote:
It doesn't work properly for me on Leopard (32-bit mode):

   > x <- c(rep(1800000003L, 10000000), -rep(1200000002L, 15000000))
   > sum(as.double(x))
   [1] 0
   > sum(x)
   [1] 4996000
   > sessionInfo()
   R version 2.14.0 RC (2011-10-27 r57452)
   Platform: i386-apple-darwin9.8.0/i386 (32-bit)

   locale:
   [1] C

   attached base packages:
   [1] stats     graphics  grDevices utils     datasets  methods   base

It looks like the problem is that isum() (in src/main/summary.c)
uses a 'double' internally to do the sum, whereas rsum() and csum()
use a 'long double'.

Note that isum() seems to be assuming that NA_INTEGER and NA_LOGICAL
will always be the same (probably fine) and that TRUE values in the
input vector are always represented as a 1 (not so sure about this one).

A more fundamental question: is switching back and forth between
'int' and 'double' (or 'long double') the right thing to do for doing
"safe" arithmetic on integers?

Thanks!
H.