How can I do something like double a polynomial?
I have this:
b <- function(ftn){2*ftn}
b(function(x) x)
But I get Error in 2 * ftn : non-numeric argument to binary operator
Is there some sort of x <-2x replacement I can do?
Sorry I'm a complete beginner.
Yes, but you do it by returning an anonymous function that takes the x
value, calls ftn
and applies the transformation. e.g. for f(x) ↦ 2f(x)
:
> doublePoly <- function(ftn) { function(x) { 2 * ftn(x) } }
> f <- function(x) {x^2 + 1}
> g <- doublePoly(f)
> c(f(1), g(1))
[1] 2 4
> c(f(3), g(3))
[1] 10 20
One can use this technique to do arbitrary transformations, e.g. multiplying by 1+x
:
mult.1plusx <- function(ftn) { function(x) { (1+x) * ftn(x) } }
Or adding exp(x)
to the logarithm of the function:
exp.plus.log <- function(ftn) { function(x) { exp(x) + log(ftn(x)) } }