rnorouzian
rnorouzian

Reputation: 7517

Solving (determining) a function at a point in R

In my below R code, I was wondering how I could find out what is rh1 when y == 0.5?

Note that y uses atanh(rh1), which can be converted back to rh1 using tanh().

rh1 <- seq(-1, 0.1, by = 0.001)
y <- pnorm(-0.13, atanh(rh1), 0.2)
plot(rh1, y, type = "l")

Upvotes: 3

Views: 155

Answers (2)

Zheyuan Li
Zheyuan Li

Reputation: 73415

Analytical solution

For a normal distribution X ~ N(mu, 0.2). We want to find mu, such that Pr (X < -0.13) = y.

Recall your previous question and my answer over there: Determine a normal distribution given its quantile information. Here we have something simpler, as there is only one unknown parameter and one piece of quantile information.

Again, we start by standardization:

   Pr {X < -0.13} = y
=> Pr { [(X - mu) / 0.2] < [(-0.13 - mu) / 0.2] } = y
=> Pr { Z < [(-0.13 - mu) / 0.2] } = y    # Z ~ N(0,1)
=> (-0.13 - mu) / 0.2 = qnorm (y)
=> mu = -0.13 - 0.2 * qnorm (y)

Now, let atanh(rh1) = mu => rh1 = tanh(mu), so in short, the analytical solution is:

tanh( -0.13 - 0.2 * qnorm (y) )

Numerical solution

It is a root finding problem. We first build the following function f, and we aim to find its root, i.e., the rh1 so that f(rh1) = 0.

f <- function (rh1, y) pnorm(-0.13, atanh(rh1), 0.2) - y

The simplest root finding method is bisection method, implemented by uniroot in R. I recommend you reading Uniroot solution in R for how we should work with it in general.

curve(f(x, 0.5), from = -1, to = 0.1); abline (h = 0, lty = 2)

We see there is a root between (-0.2, 0), so:

uniroot(f, c(-0.2, 0), y = 0.5)$root
# [1] -0.129243

Upvotes: 4

G5W
G5W

Reputation: 37661

Your function is monotonic so you can just create the inverse function.

rh1 <- seq(-1,.1,by=.001)
y <- pnorm(-.13,atanh(rh1),.2)

InverseFun = approxfun(y, rh1)
InverseFun(0.5)
[1] -0.1292726

Upvotes: 3

Related Questions