Lea
Lea

Reputation: 197

Compute the inverse of function

I want to compute and plot the inverse of given function f. I have the following code in R :

############## Parameters ###### 
r1 <- 0.0125
r2 <- 0.0305
S1 <- 0.0400
S2 <- 0.0900
s1 <- sqrt(S1)
s2 <- sqrt(S2)

rho <- -0.45
############## function f ###########
f <- function(u) ((((u-r2)/(r1-r2))^2)*((s1)^2)) + 
       (((1-((u-r2)/(r1-r2)))^2)*((s2)^2)) + 
       (2*(((u-r2)/(r1-r2)))*(1-((u-r2)/(r1-r2)))*rho*s1*s2)

f(r1)

#### the values is equal to 0.04

The problem is how to invert this function, I try to use the function uniroot but I was not able to solve my problem. this was the code that I used :

########  First I define the function inverse :

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


######## second I define the inverse of f using inverse

    f_inverse = inverse(function (u) f(u),  0.0, 0.035)

Thanks for your help,

Upvotes: 3

Views: 6667

Answers (1)

shadow
shadow

Reputation: 22293

So you are trying to invert a function that is not bijective. Look at curve(f, 0, 0.035) and abline(h=0.04, col="red") to see that. If you give uniroot proper bounds, the following will work:

f_inverse <- function(y, lower=0.0, upper=0.02) 
   uniroot((function (x) f(x) - y), lower = lower, upper = upper)$root

f_inverse(0.04)
## [1] 0.01250961

f_inverse(0.04, 0.02, 0.04) # to get the other root...
## [1] 0.02561455

EDIT: Careful, the 0.02 was really just a guess. To find the actual value, use optimize(f, lower=0, upper=1). Then you can also plot the "inverse" function:

optim <- optimize(f, lower=0, upper=1)
seq1 <- seq(f(0), optim$objective, length=100)
inv1 <- sapply(seq1, f_inverse, lower=0, upper=optim$minimum)
seq2 <- seq(optim$objective, f(0.04), length=100)
inv2 <- sapply(seq2, f_inverse, lower=optim$minimum, upper=1)
plot(c(seq1, seq2), c(inv1, inv2), type="l")

On the other hand, this doesn't seem to have any advantages over curve(f, 0, .04), which is much easier.

Upvotes: 4

Related Questions