package com.imsl.test.example.math; import com.imsl.math.*; /** *
* MinConNLP Example 2: Solves a general nonlinear programming problem with * a user supplied gradient.
* * In this example, a general nonlinear programming problem is solved using a * user-supplied gradient. The problem is as follows: ** $${\rm {min}} \,\, F(x) = (x_1 - 2)^2 + (x_2 - 1)^2$$
** subject to
* *
* $$g_1(x) = x_1 - 2x_2 + 1 = 0$$
* $$g_2(x) = -x_1^2 / 4 - x_2^2 + 1 \ge 0$$
*
* This function is called by MinConNLP
.
*
double
array containing the variable values
* @param iact an int
specifying the return value. If
* iact=0
this function returns the objective function
* evaluated at x
. If iact
=\(1, 2, 3,...\), this
* function returns the constraint with that index evaluated at
* x
.
* @param ierr a boolean
array of length 1, where
* ierr[0]=false
when no error or undesirable condition occurs
* during evaluation, and ierr[0]=true
indicates some issue
* during evaluation
* @return a double
the value specified by iact
*
*/
@Override
public double f(double[] x, int iact, boolean[] ierr) {
double result;
ierr[0] = false;
if (iact == 0) {
result = (x[0] - 2.e0) * (x[0] - 2.e0)
+ (x[1] - 1.e0) * (x[1] - 1.e0);
return result;
} else {
switch (iact) {
case 1:
result = (x[0] - 2.e0 * x[1] + 1.e0);
return result;
case 2:
result = (-(x[0] * x[0]) / 4.e0 - (x[1] * x[1]) + 1.e0);
return result;
default:
ierr[0] = true;
return 0.e0;
}
}
}
/**
* Defines the gradients of the objective and the constraints.
*
* @param x a double
array containing the variable values
* @param iact an int
specifying what should be returned. If
* iact=0
the gradient is returned evaluated at x
.
* Otherwise, the gradient of the constraint with given index
* iact=1,2,..
evaluated at x
is returned.
* @param result a double
array containing results on output
*/
@Override
public void gradient(double[] x, int iact, double[] result) {
if (iact == 0) {
result[0] = 2.e0 * (x[0] - 2.e0);
result[1] = 2.e0 * (x[1] - 1.e0);
} else {
switch (iact) {
case 1:
result[0] = 1.e0;
result[1] = -2.e0;
break;
case 2:
result[0] = -0.5e0 * x[0];
result[1] = -2.e0 * x[1];
break;
}
}
}
public static void main(String args[]) throws Exception {
int m = 2;
int me = 1;
int n = 2;
MinConNLP minconnon = new MinConNLP(m, me, n);
minconnon.setGuess(new double[]{2., 2.});
MinConNLPEx2 grad = new MinConNLPEx2();
double x[] = minconnon.solve(grad);
System.out.println("x is " + x[0] + " " + x[1]);
}
}