Reputation: 31
F = –y + 2x – ln (x/2)
s.t. –x – ln (x/2) + y ≤ 0
x ∈ [0.5, 1.4]
y ∈ {0, 1}
optimal solution: F∗ = 2.1247, x = 1.375, y = 1
How can I find this optimal solution for this nonlinear equation with optimization in R?
I tried this:
fn <- function(x,y){
f <- -x-log(x/2)+y
return(c(f))
}
fn2 <- function(z) crossprod(fn(z[1],z[2]) - c(0))
psoptim(c(1,1),fn2)
Upvotes: 2
Views: 132
Reputation: 14331
There are several good Python Nonlinear Programming packages. One option is to use reticulate
to run the Python function in R.
Save as script.py
from gekko import GEKKO
m = GEKKO()
x = m.Var(lb=0.5,ub=1.4)
y = m.Var(lb=0,ub=1,integer=True)
m.Equation(-x-m.log(x/2)+y<=0)
F = -y+2*x-m.log(x/2)
m.Minimize(F)
m.options.SOLVER=1
m.solve(disp=False)
print(m.options.OBJFCNVAL)
print(x.value[0])
print(y.value[0])
Run code in R
library(reticulate)
py_run_file("script.py")
The script produces the result:
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 4.379999998491257E-002 sec
Objective : 2.12446758455087
Successful solution
---------------------------------------------------
2.1244675846
1.3748225282
1.0
The objective function is a little different than the comment: optimal solution: F∗ = 2.1247, x = 1.375, y = 1
.
Upvotes: 1