Why does **0.5 appear to be more efficient than sqrt() [closed]

醉酒当歌 提交于 2019-11-29 12:34:37

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!