使用 scipy.optimize.linprog 进行线性规划 [英] Linear programming with scipy.optimize.linprog

查看:40
本文介绍了使用 scipy.optimize.linprog 进行线性规划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用 scipy.optimize.linprog 检查了简单的线性规划问题:

1*x[1] + 2x[2] ->最大限度1*x[1] + 0*x[2] <= 50*x[1] + 1*x[2] <= 51*x[1] + 0*x[2] >= 10*x[1] + 1*x[2] >= 11*x[1] + 1*x[2] <= 6

得到了非常奇怪的结果,我预计 x[1] 将是 1 而 x[2] 将是 5,但是:

<预><代码>>>>打印优化.linprog([1, 2], A_ub=[[1, 1]], b_ub=[6], bounds=(1, 5), method='simplex')状态:0松弛:数组([ 4., 4., 4., 0., 0.])成功:正确乐趣:3.0x: 数组([ 1., 1.])消息:'优化成功终止.'尼特:2

谁能解释一下,为什么我得到了这个奇怪的结果?

解决方案

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

这篇关于使用 scipy.optimize.linprog 进行线性规划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆