Solving for the inverse of a function in R

I cannot comment as my reputation is too low. I am a newbie to R, and it took me a while to understand Mike's code as I was not used to the way functions are defined in his answer. Below is Mike's code in a longer, but (to me) easier readable notation:

inverse <- function(f, lower, upper){
  function(y){
    uniroot(function(x){f(x) - y}, lower = lower, upper = upper, tol=1e-3)[1]
  }
}
square_inverse <- inverse(function(x){x^2}, 0.1, 100)
square_inverse(4)

I hope it helps others newbies as well.


What kind of inverse are you finding? If you're looking for a symbolic inverse (e.g., a function y that is identically equal to sqrt(x)) you're going to have to use a symbolic system. Look at ryacas for an R library to connect with a computer algebra system that can likely compute inverses, Yacas.

Now, if you need only to compute point-wise inverses, you can define your function in terms of uniroot as you've written:

> inverse = function (f, lower = -100, upper = 100) {
   function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]
}

> square_inverse = inverse(function (x) x^2, 0.1, 100)

> square_inverse(4)
[1] 1.999976

For a given y and f(x), this will compute x such that f(x) = y, also known as the inverse.

Tags:

R

Inverse