Search code examples
rfunctionoptimizationequation

Using `optimize` to solve for X in an equation in R


Below, I wonder how to find the value of x which I expect to be about .2?

f = function(x, y = 0.07925971) pnorm(x) - pnorm(0) == y

# Tried:
optimize(f, c(-4,4))

# Tried:
uniroot(f, interval = c(-4,4))

Solution

  • Update

    If you want to use optimize anyway, you should reformulate your objective function first, e.g.,

    > f <- function(x, y = 0.07925971) abs(pnorm(x) - pnorm(0) - y)
    
    > optimize(f, c(-4, 4))
    $minimum
    [1] 0.2000078
    
    $objective
    [1] 3.058234e-06
    

    Closed-form Solution

    I guess you can have a closed-form solution for x using qnorm, so, no need to use optimize or uniroot

    > f <- function(y = 0.07925971) qnorm(pnorm(0) + y)
    
    > f()
    [1] 0.2