a ^ 2和^ 2L之间有区别吗?

Sev*_*eux 1 r

有没有之间的差异a^2,并a^2L[R

速差?

精确?

到目前为止,我没有看到,只是想知道^ 2是作为log/exp对实现的,而是^ 2L作为乘法.如果a不仅仅是一个向量呢?

UPDATE

不,这不是重复,我知道2和之间的区别2L.问题是,这种差异是否对电力运营商起作用?

Mic*_*ico 6

我的结论是,它是不断所谓稍微当且仅当该基地是一个整数,以及,对标量.

我的基准:

library(microbenchmark)
set.seed(1230)
num <- rnorm(1L)
int <- sample(100L, 1L)
microbenchmark(times = 100000L,
               num^2L,
               num^2,
               int^2L,
               int^2)
Run Code Online (Sandbox Code Playgroud)

和我的机器上的时间:

# Unit: nanoseconds
#    expr min  lq     mean median  uq      max neval
#  num^2L  99 115 161.8495    121 166    11047 1e+05
#   num^2  97 113 196.8615    119 165  3645369 1e+05
#  int^2L  89 107 140.3745    111 120     3319 1e+05
#   int^2  98 115 525.1727    120 166 34776551 1e+05
Run Code Online (Sandbox Code Playgroud)

如果base或exponent是数字,则中值时间基本相同(尽管可能num ^ num有一个胖的上尾?).

规模的惩罚

尽管有integer ^ integer标量的优点,但似乎(正如@ A.Webb在他自己的答案中所阐述的那样),对于任何合理大小的向量,numeric ^ numeric它更快,并且对于相当常见的中等大小范围的向量,它会快得多.

500个基准测试的结果:

set.seed(1230)
ns <- as.integer(10^(seq(0, 6, length.out = 500L)))
mbs <- sapply(ns, function(n){
  num = rnorm(n); int = as.integer(num)
  summary(microbenchmark(times = 2000L, num ^ 2L, num ^ 2, int ^ 2L, int ^ 2), 
          unit = "relative")$median
})
Run Code Online (Sandbox Code Playgroud)

5K

第一个情节得到了事物的要点.n手段numerici手段integer.

最终,矢量大小的固定成本确实蚕食了它的优势:

1E6

只有微不足道的长度才是i ^ i最快的:

50


绘图的要点是这样的:

matplot(ns[ns < 5000], t(mbs[ , ns < 5000]),
        type = "l", lty = 1L, lwd = 3L,
        xlab = "length", ylab = "Relative Time",
        main = "Through Length 5000",
        col = c("black", "red", "green", "blue"))
legend("topleft", c("n ^ i", "n ^ n", "i ^ i", "i ^ n"),
       col = c("black", "red", "green", "blue"),
       lty = 1L, lwd = 3L)
Run Code Online (Sandbox Code Playgroud)