Skip to content

Instantly share code, notes, and snippets.

@b3z
Last active November 26, 2021 06:44
Show Gist options
  • Save b3z/d61e0611e0afad537c62996ed2d5336c to your computer and use it in GitHub Desktop.
Save b3z/d61e0611e0afad537c62996ed2d5336c to your computer and use it in GitHub Desktop.
Apache Commons math3 Simplex solver example
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.optim.MaxIter;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.optim.linear.LinearConstraint;
import org.apache.commons.math3.optim.linear.LinearConstraintSet;
import org.apache.commons.math3.optim.linear.LinearObjectiveFunction;
import org.apache.commons.math3.optim.linear.NonNegativeConstraint;
import org.apache.commons.math3.optim.linear.Relationship;
import org.apache.commons.math3.optim.linear.SimplexSolver;
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType;
public class SimplexExample {
public static void main(String[] args) {
LinearObjectiveFunction func = new LinearObjectiveFunction(new double[] {1, -1 ,-1}, 0);
Collection <LinearConstraint> constraints = new ArrayList <LinearConstraint> ();
// LGS constraints
constraints.add(new LinearConstraint(new double[] {2, 4, 2},Relationship.EQ, 4));
constraints.add(new LinearConstraint(new double[] {4, 12, 5},Relationship.EQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(
new MaxIter(100), // stop after a hundred iterations
func, // given function
new LinearConstraintSet(constraints), // constraints
GoalType.MINIMIZE, // we want to minimize
new NonNegativeConstraint(true)); // x1, x2x, x3 >= 0
System.out.println(solution.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment