trying to optimize a equation in the interval 1 to 4

Viewed 40

Trying to optimize a equation in the interval 1 to 4 but the minimum value of x and y is coming out to be wrong.


x <- seq(from=1, to=4, by=0.1)
y <- ((x^2)+(54/x))
df <- data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_line()

optimize(y, interval = c(1,4))

enter image description here

RStudio window with code equation graph and minimum values of x and y

1 Answers

The first argument of optimize() needs to be a function, e.g.

optimize(function(x) {x^2 + 54/x}, interval = c(1,4))
$minimum
[1] 2.99999

$objective
[1] 27

If you print the value of y you'll see that it's a vector, not a function. You could use x[which.min(y)] to find the value of x that corresponds to the minimum of the particular values of x that you have evaluated.

Related