run run chicken
run run chicken

Reputation: 503

Automatic conversion from integer to numeric during integer calculation in R?

Here are two snippets:

a = 1:1000000; res = as.integer(0);
class(res)
system.time(for (e in a) res = res + e ^ 2)
class(res)

###########################
fn1 <- function (N) 
{
  for(i in 1:N) {
    y <- i*i
  }
}
print (fn1(1000000))

The bottom snippet is from this post: For-loop vs while loop in R

The bottom snippet works as expected, there is integer overflow, because big number when squared are over the boundary of integers.

However the top snippets produce this result:

> a = 1:1000000; res = as.integer(0);
> class(res)
[1] "integer"
> system.time(for (e in a) res = res + e^2)
   user  system elapsed 
  0.411   0.001   0.412 
> class(res)
[1] "numeric"
> print (res)
[1] 3.333338e+17

My question is: why is res changed from "integer" to "numeric"?

Upvotes: 1

Views: 176

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73405

Because power operation ^ returns floating point number in double precision.

typeof( (2L) ^ 2 )
#[1] "double"

typeof( (2L) ^ (2L) )
#[1] "double"

If you do want to use it in your integer overflow experiment, use

res = res + as.integer(e ^ 2)

lmo has got you the R documentation ?"^" (or ?Arithmetic):

If both arguments are of type integer, the type of the result of / and ^ is numeric and for the other operators it is integer (with overflow, which occurs at +/- (2^31 - 1), returned as NA_integer_ with a warning).

Upvotes: 2

Related Questions