Severin Pappadeux - 1 year ago 75
R Question

# Is there a difference between a^2 and a^2L?

Is there a difference between

`a^2`
and
`a^2L`
in R?

Speed difference?

Precision?

So far I see none, just wondering if ^2 is implemented as log/exp pair, but ^2L as a multiplication. What about if
`a`
is not just a vector?

UPDATE

No, it is NOT a duplicate, I know about difference between
`2`
and
`2L`
. Question is, does this difference play a role for the power operator?

R uses an integer exponent version `R_pow_di` internally, but the `^` operator only calls `R_pow`. That being said, `R_pow` does special case `x^2` as `x*x`. Therefore, the precision is identical, but the `2L` version ought to be slightly slower due to long->double coercion at the C level. This is demonstrated in the following benchmark.

``````> lngs<-rep(2L,1e6)
> dbls<-rep(2.0,1e6)
> n<-sample(100,1e6,replace=TRUE)
> x<-rnorm(1e6)
> microbenchmark(x^lngs,x^dbls,n^lngs,n^dbls)
Unit: milliseconds
expr       min        lq      mean    median       uq      max neval cld
x^lngs  8.489547  9.804030 12.543227 11.719721 13.98702 19.92170   100  b
x^dbls  5.622067  6.724312  9.432223  7.949713 10.89252 59.15342   100 a
n^lngs 10.590587 13.857297 14.920559 14.200080 16.65519 19.55346   100   c
n^dbls  8.331087  9.699143 12.414267 11.403211 14.20562 19.66389   100  b
``````

This is nothing to lose sleep over.

Links go to the source mirror. Note that `R_ADD`, `R_SUB`, `R_MUL` and `R_DIV` are defined as C macros to take advantage of type overloading, but `R_POW` is defined to inline the `x^2 = x*x` special case then calls `R_pow` (lower case). The checking for that special case again in `R_pow` would be duplicative except that `R_pow` is called internally other places.