Search code examples
rminimum

How to find x's (more than one) that minimize a function in r


hx <- function(x){
  abs(16*x*exp(1)^(-4*x) - 0.55)
}

roots_gx <- optimize(hx, lower = 0, upper = 2)$minimum
roots_gx

One of the roots of g(x) is 0.78, struggling to find the other one

tried this code:

roots_gx <- optimize(hx, lower = 0, upper = 2)$minimum
roots_gx 

I was expecting two answers only got one


Solution

  • First graph the function and use the appropriate intervals to obtain the solutions:

    curve(hx) # perhaps use l2 norm instead of l1 norm.
    

    enter image description here

    Now we could obtain the two solutions:

    optimize(hx, lower = 0, upper = 0.5)$minimum
    [1] 0.04040332
    optimize(hx, lower = 0.5, upper = 1)$minimum
    [1] 0.7807179
    

    But this is a well defined function. Use the lambertW function with its 2 branches to obtain the two solutions:

    LambertW::W(-0.55/4)/-4
    [1] 0.04040481
    LambertW::W(-0.55/4, -1)/-4
    [1] 0.7807226
    

    These solutions are the true solutions as compared to the optimization above