#导入包
from scipy import optimize
import numpy as np
#确定c,A,b,Aeq,beq
c = np.array([115,90])
A = np.array([[10,20],[4,16],[15,10]])
b = np.array([200,128,220])
#Aeq = np.array([[1,-1,1]])
#beq = np.array([2])
#求解
res = optimize.linprog(-c,A,b)
print(res)
输出结果:
大M法:#导入包
from scipy import optimize
import numpy as np
#确定c,A,b,Aeq,beq
c = np.array([2,1,1])
A = np.array([[0,2,-1],[0,1,-1]])
b = np.array([-2,1])
Aeq = np.array([[1,-1,1]])
beq = np.array([2])
#求解
res = optimize.linprog(-c,A,b,Aeq,beq)
print(res)
结果如下:
拉格朗日乘子法:from scipy.optimize import minimize
import numpy as np
e = 1e-10 # 非常接近0的值
fun = lambda x : 8 * (x[0] * x[1] * x[2]) # 约束函数f(x,y,z) =8 *x*y*z
cons = ({'type': 'eq', 'fun': lambda x: x[0]**2+ x[1]**2+ x[2]**2 - 1}, # x^2 + y^2 + z^2=1
{'type': 'ineq', 'fun': lambda x: x[0] - e}, # x>=e,即 x > 0
{'type': 'ineq', 'fun': lambda x: x[1] - e},
{'type': 'ineq', 'fun': lambda x: x[2] - e}
)
x0 = np.array((1.0, 1.0, 1.0)) # 设置初始值
res = minimize(fun, x0, method='SLSQP', constraints=cons)
print('最大值:',res.fun)
print('最优解:',res.x)
print('迭代终止是否成功:', res.success)
print('迭代终止原因:', res.message)
结果如下: