power.RdGiven a function \(f\colon X\longrightarrow X\), we define
$$f^0 = \mathrm{id_X}$$
$$f^{n+1} = f\circ f^n=f^n\circ f,\qquad n\geqslant 0$$
This gives us \(f^{n+m}=f^n\circ f^m\) and \(\left(f^m\right)^n=f^{mn}\), which motivates the notation. For example, \(\sin^3=\sin\circ\sin\circ\sin\), so \(\sin^3(x)=\sin(\sin(\sin x))\).
The operator is well-defined due to the power associativity of function composition.
pow(x, n)Returns an object of class vf
There are possibly more efficient methods requiring fewer
compositions, e.g. pow(f,9) (which would require 8 function
compositions) could be evaluated by pow(pow(f,3),3) (which
requires only four). But I am not sure that this would actually be
any faster, and I have not got round to thinking about it yet.
Also, package idiom for the caret “^” is reserved for
arithmetic exponentiation [so, for example, (f^3)(x) ==
f(x)*f(x)*f(x)]. I believe this is sub-optimal but was unable to
overload the caret to implement functional iteration.
pow(Sin, 5)
#> An object of class "vf"
#> function (o)
#> {
#> Sin(x(o))
#> }
#> <bytecode: 0x55a96b368f78>
#> <environment: 0x55a96958e3e8>
Sin^5
#> An object of class "vf"
#> function (...)
#> {
#> e1(...)^e2
#> }
#> <bytecode: 0x55a969178398>
#> <environment: 0x55a969178c58>
f <- as.vf(function(x){x^2+1})
pow(f+Sin, 4)
#> An object of class "vf"
#> function (...)
#> {
#> e1(...) + e2(...)
#> }
#> <bytecode: 0x55a96b72d848>
#> <environment: 0x55a96a62f718>
pow(f+Sin, 4)(2)
#> [1] 1598423