Search code examples
rroot

no sign change found in 1000 iterations in R


my question is "Find the maximum of the function myfun = - (sin(x)-3)^2 + 1 ,on the interval (0,5), and please answer x=? and f(x)= ?"

there is my code in R:

f <- function(x) { return((-1*sin(x)-3)^2+1 }
result <- uniroot(f,c(0,5),extendInt = "yes"
result$root
result$f.root

but the console is :

Error in uniroot(f, c(0, 5), extendInt = "yes") : no sign change found in 1000 iterations

what's wrong with my code Thanks a lot


Solution

  • optimize is the standard function for finding a max or min of a 1-dimensional function. uniroot is used for finding a root (0) of the function, not max or min values.

    optimize(f, interval = c(0, 5), maximum = TRUE)
    $maximum
    [1] 1.570796
    
    $objective
    [1] 17
    

    See ?optimize for examples and details.

    (Note: I added a ) to the f in your question to avoid syntax errors.)