lpSolve与linprog求解线性规划结果差异大,是否为实现问题?
linprog and R's lpSolve Give Divergent Results for Your LP The massive discrepancy you're seeing has nothing to do with inherent implementation flaws—it's a parameter misusage in your Scipy code that's causing you to solve two completely different linear programs. Let's break this down:
Core Issue: Misapplied Constraints in Scipy
Scipy's linprog has strict parameter definitions for constraints:
- The second and third arguments (
A_ub,b_ub) are for inequality constraints of the formA_ub @ x ≤ b_ub - To specify equality constraints, you need to use the
A_eqandb_eqkeyword arguments instead.
In your Python code, you passed all your equality constraints to A_ub and b_ub:
res = linprog(obj_func, constraints, rhs, method="interior-point", options={"disp":True})
This tells Scipy to solve:
minimize x1 + x2 + x3 subject to: x1 ≤ 0.4498162 x2 ≤ 0.4498162 x3 ≤ 0.1003676 x1 + x2 + x3 ≤ 1.0
The optimal solution here is obviously making x1, x2, x3 as small as possible (near zero), which matches the tiny objective value you got from linprog.
Meanwhile, your R code correctly specifies equality constraints with f.dir = c("=","=","=","="), solving the actual problem you intended:
minimize x1 + x2 + x3 subject to: x1 = 0.4498162 x2 = 0.4498162 x3 = 0.1003676 x1 + x2 + x3 = 1.0
Here, the constraints force x1, x2, x3 to fixed values, so the objective function is 0.4498 + 0.4498 + 0.1003 ≈ 1—exactly what lpSolve returns.
Fixing the Scipy Code
To get matching results, rewrite your linprog call to use the A_eq and b_eq parameters:
import numpy as np from scipy.optimize import linprog obj_func = [1,1,1] constraints = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]]) rhs = [0.4498162176582741, 0.4498162176582741, 0.10036756468345168, 1.0] # Pass equality constraints to A_eq and b_eq res = linprog(obj_func, A_eq=constraints, b_eq=rhs, method="interior-point", options={"disp":True}) print(res)
This will now solve the same equality-constrained LP as your R code, and you'll see an objective value close to 1 (with minor numerical precision differences, which are normal for solvers).
Why Your Other Test Cases Show Similar Differences
The same logic applies to your other systems: you're treating equality constraints as upper-bound inequalities in Scipy, leading to a trivial minimal objective (near zero), while lpSolve correctly enforces the equalities and returns the actual intended objective value.
A Quick Note on Numerical Precision
You might see tiny differences in the exact objective value between solvers (e.g., 1 vs 0.9999999999) due to floating-point arithmetic, but this is normal and not a cause for concern. The key issue here was the constraint parameter mismatch.
内容的提问来源于stack exchange,提问作者Noah16

