[R] x*x*x*... vs x^n

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jun 29 15:04:30 CEST 2005


On 6/29/2005 7:32 AM, Robin Hankin wrote:
> Hi
> 
> I have been wondering if there one can speed up calculating small powers
> of numbers such as x^8 using multiplication.
> 
> In addition, one can be a bit clever and calculate x^8 using only 3  
> multiplies.
> 
> look at this:
> 
> 
>  > f1 <- function(x){x*x*x*x*x*x*x*x}
>  > f2 <- function(x){x^8}
>  > f3 <- function(x){x2 <- x*x;x4 <- x2*x2;return(x4*x4)}
> 
> [so f1() and f2() and f3() are algebraically identical]
> 
> 
>  > a <- rnorm(1000000)
>  > system.time(ignore <- f1(a))
> [1] 0.50 0.17 2.88 0.00 0.00
> 
>  > system.time(ignore <- f2(a))
> [1] 0.31 0.03 1.40 0.00 0.00
> 
>  > system.time(ignore <- f3(a))
> [1] 0.10 0.07 0.18 0.00 0.00
> 
> 
> [these figures show little variance from trial to trial]
> 
> 
> I was expecting f2() and f3() to be about the same.
> I was not expecting a factor of 3 there!
> 
> anyone got any comments?

If you look in src/main/arithmetic.c, you'll see that R does a general 
real-valued power (using C's pow() function) whenever either one of the 
args is real (except for a few special cases, e.g. non-numbers, or 
powers of 2 or 0.5).  There is an internal R function equivalent to your 
f3, but it is not used in the situation of real^integer (and in any 
case, x^8 is real^real).

I suppose if you wanted to submit a patch someone would take a look, but 
the question is whether there is really any calculation whose execution 
time would be materially affected by this.  Most computations are not 
dominated by integer power calculations, so is this really worth the 
trouble?

Duncan Murdoch




More information about the R-help mailing list