Skip to content
Prev 42048 / 63435 Next

bug in sum() on integer vector

On Dec 14, 2011, at 16:19 , John C Nash wrote:

            
It (sum) does warn if you take the two "halves" separately. The issue is that the overflow is detected at the end of the summation, when the result is to be saved to an integer (which of course happens for all intermediate sums in cumsum)
[1] NA
Warning message:
In sum(x[1:1e+07]) : Integer overflow - use sum(as.numeric(.))
[1] NA
Warning message:
In sum(x[10000001:1.5e+07]) : Integer overflow - use sum(as.numeric(.))
[1] 4996000

There's a pretty easy fix, essentially to move

    if(s > INT_MAX || s < R_INT_MIN){
        warningcall(call, _("Integer overflow - use sum(as.numeric(.))"));
        *value = NA_INTEGER;
    }

inside the summation loop. Obviously, there's a speed penalty from two FP comparisons per element, but I wouldn't know whether it matters in practice for anyone.