Why does **0.5 appear to be more efficient than sq

2019-01-27 05:39发布

问题:

I have tried measuring the speed of these two ways for taking square root:

> system.time(expr = replicate(10000, 1:10000 ** (1/2)))
##   user  system elapsed 
##  0.027   0.001   0.028 
> system.time(expr = replicate(10000, sqrt(1:10000)))
##   user  system elapsed 
##  3.722   0.665   4.494 

If the sqrt() function cannot compete with ** 0.5, why do we need such a function?

(system is OS X Yusemite, and R version is 3.1.2)

回答1:

You forgot important parentheses. Here are the timings after correcting that:

system.time(expr = replicate(10000, (1:10000) ** (1/2)))
#user  system elapsed 
#4.76    0.32    5.12 
system.time(expr = replicate(10000, sqrt(1:10000)))
#user  system elapsed 
#2.67    0.57    3.31


回答2:

To add to @Roland's answer, you fell into the Operators precedence "trap". ^ comes before : ("** is translated in the parser to ^" as per documentation of ?"**")

What really happened is

`:`(1, 10000 ** (1/2))

That means that first you've run ** and only then 1:..

A tip for the future, try to debug your code before running sophisticated operations, for example, testing

1:5 ** (1/2)
## [1] 1 2
sqrt(1:5)
## [1] 1.000000 1.414214 1.732051 2.000000 2.236068 

Would reveal the issue.