Apache commons 数学 3:构建模型时总是出现 UnboundedSolutionException

Apache commons math 3: always getting UnboundedSolutionException when constructing a model

我想用 apache 的 commons math 3 解决以下模型:

maximize: 30x + 40y
s.t. x+y <= 240; 2x+y <= 320; x,y>=0;

我的代码,与文档相关应该是:

        // objective f = 30x + 40y + 0
        LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 30, 40},0);


        List<LinearConstraint> constraints = new ArrayList();

        // x + y <= 240
        constraints.add(new LinearConstraint(new double[] {1, 1}, Relationship.LEQ, 240));
        // x + y <= 320
        constraints.add(new LinearConstraint(new double[] {2, 1}, Relationship.LEQ, 320));
        // x,y >=0
        NonNegativeConstraint nonNegativeConstraint = new NonNegativeConstraint(false);


        LinearConstraintSet constraintSet = new LinearConstraintSet(constraints);
        SimplexSolver linearOptimizer = new SimplexSolver();
        // put everything together in order to get a maximization problem
        // in the next line i receive org.apache.commons.math3.optim.linear.UnboundedSolutionException: unbounded solution
        PointValuePair solution = linearOptimizer.optimize(f, constraintSet, GoalType.MAXIMIZE, nonNegativeConstraint);


        if (solution != null) {
            //get solution
            double max = solution.getValue();
            System.out.println("Opt: " + max);
        }

但是每次调用 linearOptimizer.optimize 时,我都会得到:org.apache.commons.math3.optim.linear.UnboundedSolutionException。文档说:

public class UnboundedSolutionException extends MathIllegalStateException This class represents exceptions thrown by optimizers when a solution escapes to infinity.

但我已经用 LPSolve 的 GUI 解决了这个优化问题,它给了我解决方案 x=0; y=240; f(x,y)=9600。所以我想,我做错了什么。

1) 知道吗,我做错了什么?

2) 我已阅读 this post, which is 4 years ago and was written with the commons math library (not , math3). Is there now a possibility to say, that some decision variables should be integer, binary etc.? Otherwise i would programm the Branch and Bound -appoach 手动实现。

如果你能提供帮助和任何想法,我将非常高兴。

非常感谢:-)

从未使用过该库,但文档告诉您:

public NonNegativeConstraint(boolean restricted)

Parameters:

restricted - If true, all the variables must be positive.

而你恰恰相反:

NonNegativeConstraint nonNegativeConstraint = new NegativeConstraint(false);

阅读文档,我强烈倾向于不支持整数编程

您错误地配置了 NonNegativeConstraint,如果您希望 x,y 都为正数,您应该将 "true" 传递给它的构造函数