如何在JOptimizer中直接表示线性规划的等式约束?
How to Define Equality Constraints Directly in JOptimizer
Great question! You’re right that you can simulate equality constraints Ax = b by creating paired inequalities (Ax ≤ b and -Ax ≤ -b), but JOptimizer offers a much cleaner, direct way to handle equalities—no workarounds needed.
Direct Equality Constraint Support
The LPOptimizationRequest class has dedicated methods specifically for equality constraints:
setA(double[][] A): Defines the coefficient matrix for the equality constraintsAx = bsetB(double[] b): Defines the right-hand side vector for these equalities
Example Implementation
Let’s extend your original linear program to include an equality constraint (e.g., x₁ + x₂ = 1.5) to show how this works in practice:
// Objective function: maximize x1 + x2 (equivalent to minimizing -x1 -x2) double[] c = new double[] { -1., -1. }; // Inequalities constraints (your original set) double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}}; double[] h = new double[] {2., 1./2., 2., 1./2.}; // Equality constraint: x1 + x2 = 1.5 double[][] A = new double[][] {{1., 1.}}; // Coefficient matrix for Ax = b double[] b = new double[] {1.5}; // Right-hand side vector for equalities // Bounds on variables double[] lb = new double[] {0 , 0}; double[] ub = new double[] {10, 10}; // Optimization problem setup LPOptimizationRequest or = new LPOptimizationRequest(); or.setC(c); or.setG(G); or.setH(h); or.setA(A); // Attach equality constraint matrix or.setB(b); // Attach equality constraint RHS or.setLb(lb); or.setUb(ub); or.setDumpProblem(true); // Execute optimization LPPrimalDualMethod opt = new LPPrimalDualMethod(); opt.setLPOptimizationRequest(or); opt.optimize();
Why This Approach Is Better
- Readability: Your code explicitly states you’re using an equality constraint, rather than hiding the logic behind paired inequalities.
- Reduced Risk of Error: No chance of mixing up signs when creating the
-Ax ≤ -bcounterpart. - Potential Efficiency: The solver can handle equality constraints natively, which may lead to better performance compared to solving an expanded set of inequalities.
All recent stable versions of JOptimizer support this feature, so you won’t have to worry about compatibility issues.
内容的提问来源于stack exchange,提问作者Yu Gu
相关产品推荐
相关产品推荐

