You may be interested in solving general non-linear optimization problems where the constraints are not linear. The solnp()
function from the Rsolnp
package allows you to solve general non-linear programming problems. For example, say we wanted to minimize the function subject to the constraint .
First, we install and load the package as follows:
> install.packages("Rsolnp") > library("Rsolnp") # We also suggest taking a look at the help page for the function arguments and restriction > help(solnp)
Then, we store our function to minimize f
as follows:
> f <- function(x){ 4*x[1] - 2*x[2] }
We need to store our constraint function in a separate object as follows:
> ctr <- function(x){ x[1]^2 + x[2]^2 }
Next, we store the value on the right-hand side of the constraint equation in a separate object as follows:
> constraints <- c(41)
Then, we store the initial parameters for and in x0
as follows:
> x0 <- c(1, 1)
We are ready to solve the problem with the solnp()
function. We use eqfun
for the constraint function and eqB
for the constraint as follows:
> gnlp1 <- solnp(x0, fun = f, eqfun = ctr, eqB = constraints) Iter: 1 fn: 4.8490 Pars: 7.97483 13.52517 Iter: 2 fn: -89.3900 Pars: -13.15464 18.38573 Iter: 3 fn: -75.5164 Pars: -17.70654 2.34511 Iter: 4 fn: -50.6915 Pars: -9.26314 6.81945 Iter: 5 fn: -34.8293 Pars: -7.33659 2.74148 Iter: 6 fn: -29.4963 Pars: -5.79341 3.16135 Iter: 7 fn: -28.6698 Pars: -5.74107 2.85273 Iter: 8 fn: -28.6358 Pars: -5.72713 2.86361 Iter: 9 fn: -28.6356 Pars: -5.72713 2.86356 Iter: 10 fn: -28.6356 Pars: -5.72713 2.86356 solnp--> Completed in 10 iterations
We can obtain the values for x and y that minimize the function with $par
as follows:
> gnlp1$par [1] -5.727129 2.863564
Now let's say we wanted to minimize subject to the constraint . All we need to do is use ineqfun
for the constraint function and set the ineqLB
argument's lower boundary to 0
and the ineqUB
argument to 45
in the solnp()
function. For simplicity, we will set the initial parameters to (-5, 5)
as follows:
> x0 <- c(-5, -5) > gnlp2 <- solnp(x0, fun = f, ineqfun = ctr, ineqLB = c(0), ineqUB=c(45)) Iter: 1 fn: -13.6535 Pars: -5.44225 -4.05775 Iter: 2 fn: -19.9098 Pars: -6.33853 -2.72215 Iter: 3 fn: -27.9987 Pars: -7.16312 -0.32691 Iter: 4 fn: -32.6786 Pars: -6.85051 2.63826 Iter: 5 fn: -30.2915 Pars: -6.02704 3.09169 Iter: 6 fn: -30.0031 Pars: -6.00113 2.99927 Iter: 7 fn: -30.0000 Pars: -6.00000 3.00000 Iter: 8 fn: -30.0000 Pars: -6.00000 3.00000 Iter: 9 fn: -30.0000 Pars: -6.00000 3.00000 solnp--> Completed in 9 iterations > gnlp2$par [1] -6 3
18.118.128.105