scipy求解线性规划


环境搭建

使用pip安装scipy和numpy,注意numpy要符合scipy对其版本的要求:

pip3 install -U numpy==1.24.0

求解等式的整数规划

from scipy.optimize import minimize

c = [1, 2, 3, 4]

def objective_function(x):
return (x[0] - 2)**2 + (x[1] - 3)**2

# 设置整数规划问题的约束条件:变量 x[0] 和 x[1] 必须为整数,同时满足 x[0] + x[1] = 5
constraint = ({'type': 'eq', 'fun': lambda x: x[0]*c[2] + x[1]*c[3] - 5},
{'type': 'eq', 'fun': lambda x: x[0] % 1},
{'type': 'eq', 'fun': lambda x: x[1] % 1})

# 设置变量 x[0] 和 x[1] 的取值范围为整数
bounds = [(0, 10), (0, 10)]

result = minimize(objective_function, [0, 0], method='SLSQP', bounds=bounds, constraints=constraint)
print(result)

1746175706265

参考

https://zhuanlan.zhihu.com/p/611514046

https://www.cnblogs.com/youcans/p/14713335.html


文章作者: q1ming
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 q1ming !
  目录