# [Rd] sum overflow (PR#1091)

Uwe Ligges ligges@statistik.uni-dortmund.de
Thu, 13 Sep 2001 14:16:36 +0200

```Bill Simpson wrote:
>
> > It's not a problem with sum:
> >
> > > sum(a*a)
> > [1] 333833500
> > > sum(b*b)
> > [1] 333833500
> >
> > are accurate.
> >
> > The overflow is in the integer arithmetic for *.  That's a question for
> > your C run-time system.  On a 64-bit machine you might get different
> > results (although most use 32-bit ints, including mine).
> >
> > If you use integers you need to be aware of the consequences.  It's a
> > feature not a bug.
> I thought R used an internal rep that was double in all cases.
> Now I'm confused:
> > a<-(1:1000)
> > b<-(1:1000)
> > sum(a*a)*sum(b*b)
> [1] -652010736
> > a<-(1:1000)/1.0
> > b<-(1:1000)/1.0
> > sum(a*a)*sum(b*b)
> [1] 1.114448e+17
>
> So  R somehow decides whether to use an integer or a double
> representation? Please tell me the rule used by R so I will know in the
> future.

It depends on the function you are using.

In your case you could use:
as.double(sum(a*a)) * as.double(sum(b*b))

or just check if the result is double:
is.double(sum(a*a))

Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```