Book Image

Mastering Scientific Computing with R

Book Image

Mastering Scientific Computing with R

Overview of this book

Table of Contents (17 chapters)
Mastering Scientific Computing with R
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

General non-linear optimization


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...