I am trying to find the local minimum of a function, and the parameters have a fixed sum. For example,
Fx = 10 - 5x1 + 2x2 - x3
and the conditions are as follows,
x1 + x2 + x3 = 15
(x1,x2,x3) >= 0
Where the sum of x1, x2, and x3 have a known value, and they are all greater than zero. In R, it would look something like this,
Fx = function(x) {10 - (5*x[1] + 2*x[2] + x[3])}
opt = optim(c(1,1,1), Fx, method = "L-BFGS-B", lower=c(0,0,0), upper=c(15,15,15))
I also tried to use inequalities with constrOptim to force the sum to be fixed. I still think this may be a plausible work around, but I was unable to make it work. This is a simplified example of the real problem, but any help would be very appreciated.
On this occasion
optim
will not work obviously because you have equality constraints.constrOptim
will not work either for the same reason (I tried converting the equality to two inequalities i.e. greater and less than 15 but this didn't work withconstrOptim
).However, there is a package dedicated to this kind of problem and that is
Rsolnp
.You use it the following way:
Output:
So the resulting optimal values are:
which means that the first parameter is 15 and the rest zero and zero. This is indeed the global minimum in your function since the x2 is adding to the function and 5 * x1 has a much greater (negative) influence than x3 on the outcome. The choice of 15, 0, 0 is the solution and the global minimum to the function according to the constraints.
The function worked great!
This is actually a linear programming problem, so a natural approach would be to use a linear programming solver such as the
lpSolve
package. You need to provide an objective function and a constraint matrix and the solver will do the rest:Then you can access the optimal solution and the objective value (adding the constant term 10, which is not provided to the solver):
A linear programming solver should be a good deal quicker than a general nonlinear optimization solver and shouldn't have trouble returning the exact optimal solution (instead of a nearby point that may be subject to rounding errors).