0

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)

smci
  • 32,567
  • 20
  • 113
  • 146
Lytze
  • 755
  • 6
  • 12
  • See `?Syntax` for operator precedence. Exponentiation `^` has higher precedence than sequence operator `:`. Compare `1:4 ^ (0.5)`; `1:(4 ^ (0.5))`; `(1:4) ^ (0.5)` – Henrik Mar 17 '15 at 11:51
  • 4
    Before benchmarking two alternatives you should always check that they give identical results. – Roland Mar 17 '15 at 11:53

2 Answers2

13

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
Roland
  • 127,288
  • 10
  • 191
  • 288
8

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.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • 2
    ** is a somewhat common way to indicate exponentiation in other languages. That is probably how they came up with it. – Dason Mar 17 '15 at 12:19