Example 2: Solving a general nonlinear programming problem

A general nonlinear programming problem is solved using a user-supplied gradient. The problem

{\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

is solved.

using System;
using Imsl.Math;

public class MinConNLPEx2 : MinConNLP.IGradient
{
	public double F(double[] x, int iact, bool[] ierr)
	{
		double result;
		ierr[0] = false;
		if (iact == 0)
		{
			result = (x[0] - 2.0) * (x[0] - 2.0) + 
				(x[1] - 1.0) * (x[1] - 1.0);
			return result;
		}
		else
		{
			switch (iact)
			{
				
				case 1: 
					result = (x[0] - 2.0 * x[1] + 1.0);
					return result;
				
				case 2: 
					result = (-(x[0] * x[0]) / 4.0 - 
						(x[1] * x[1]) + 1.0);
					return result;
				
				default: 
					ierr[0] = true;
					return 0.0;
				
			}
		}
	}
	
	
	public void Gradient(double[] x, int iact, double[] result)
	{
		if (iact == 0)
		{
			result[0] = 2.0 * (x[0] - 2.0);
			result[1] = 2.0 * (x[1] - 1.0);
			return;
		}
		else
		{
			switch (iact)
			{
				case 1: 
					result[0] = 1.0;
					result[1] = - 2.0;
					return;
				
				case 2: 
					result[0] = - 0.5 * x[0];
					result[1] = - 2.0 * x[1];
					return;
				}
		}
	}
	

	public static void  Main(String[] args)
	{
		int m = 2;
		int me = 1;
		int n = 2;
		MinConNLP minconnon = new MinConNLP(m, me, n);
		minconnon.SetGuess(new double[]{2.0, 2.0});
		double[] x = minconnon.Solve(new MinConNLPEx2());
		new PrintMatrix("x").Print(x);
	}
}

Output

          x
           0          
0  0.822875655532512  
1  0.911437827766256  


Link to C# source.