更新时间:2023-11-25 22:21:52
optimize.linprog
总是最小化你的目标函数.如果你想最大化,你可以使用 max(f(x)) == -min(-f(x))
from scipy import 优化优化.linprog(c = [-1, -2],A_ub=[[1, 1]],b_ub=[6],界限=(1, 5),方法='单工')
这将为您提供预期的结果,值为 -f(x) = -11.0
slack: array([ 0., 4., 0., 4., 0.])消息:'优化成功终止.'尼特:3x: 数组([ 1., 5.])状态:0成功:正确乐趣:-11.0
I've just check the simple linear programming problem with scipy.optimize.linprog:
1*x[1] + 2x[2] -> max
1*x[1] + 0*x[2] <= 5
0*x[1] + 1*x[2] <= 5
1*x[1] + 0*x[2] >= 1
0*x[1] + 1*x[2] >= 1
1*x[1] + 1*x[2] <= 6
And got the very strange result, I expected that x[1] will be 1 and x[2] will be 5, but:
>>> print optimize.linprog([1, 2], A_ub=[[1, 1]], b_ub=[6], bounds=(1, 5), method='simplex')
status: 0
slack: array([ 4., 4., 4., 0., 0.])
success: True
fun: 3.0
x: array([ 1., 1.])
message: 'Optimization terminated successfully.'
nit: 2
Can anyone explain, why I got this strange result?
optimize.linprog
always minimizes your target function. If you want to maximize instead, you can use that max(f(x)) == -min(-f(x))
from scipy import optimize
optimize.linprog(
c = [-1, -2],
A_ub=[[1, 1]],
b_ub=[6],
bounds=(1, 5),
method='simplex'
)
This will give you your expected result, with the value -f(x) = -11.0
slack: array([ 0., 4., 0., 4., 0.])
message: 'Optimization terminated successfully.'
nit: 3
x: array([ 1., 5.])
status: 0
success: True
fun: -11.0