NMath User's Guide

TOC |  Previous |  Next |  Index

27.1 Solving LP Problems (.NET, C#, CSharp, Visual Basic, VB.NET)

Instances of SimplexLPSolver are constructed by specifying an error tolerance, or by accepting the default tolerance. For example, this code constructs a SimplexLPSolver with an error tolerance of 10-8:

SimplexLPSolver solver = new SimplexLPSolver( 1e-8 );

The Solve() method on SimplexLPSolver accepts a vector of coefficients representing the objective function, a matrix of constraint coefficients, a vector of right-hand sides, the number of each constraint type (in the order, number less than, number greater than, and number equal to), and optionally vectors of lower and upper variable bounds. For example, this code solves the LP problem shown above:

// the objective function
DoubleVector obj = new DoubleVector( "[1 4 9]" );

// the constraints
DoubleMatrix constraints =
  new DoubleMatrix( "3x3 [1 1 0  1 0 1  0 -1 1]" );
DoubleVector rhs = new DoubleVector( "[5 10 7]" );
int numLessThan = 1;
int numGreaterThan = 1;
int numEqual = 1;

// the variable bounds
DoubleVector lowerBounds = new DoubleVector( "[0 0 0]" );
DoubleVector upperBounds = new DoubleVector( "[4 1 Infinity]" );

SimplexLPSolver solver = new SimplexLPSolver();
DoubleVector solution = solver.Solve( obj,
                                      constraints,
                                      rhs,
                                      numLessThan,
                                      numGreaterThan,
                                      numEqual,
                                      lowerBounds,
                                      upperBounds );

NOTE- All right-hand sides must be non-negative. The default bounds are 0 to PositiveInfinity. The bounds may be restricted further, but they must remain non-negative.

It is important to check the Status property after optimization, which returns a value from the SimplexLPSolver.SolutionStatus enumeration, since your problem may be unbounded or infeasible. The IsGood property returns true if Status == SolutionStatus.FiniteSolutionFound. Thus:

if ( solver.IsGood )
{
  // ...
}

If a finite solution was found, you can access the solution using the Solution property. (The solution is also returned by the Solve() method). The OptimalValue property gets the value of the objective function evaluated at the solution.

TOC |  Previous |  Next |  Index