线性规划
示例文件
# 1.导入相关库
import numpy as np
from scipy import optimize as op
# 2.给出变量范围
x1 = (0, None)
x2 = (0, None)
x3 = (0, None)
# 3.给出相关参数
# 目标函数参数
c = np.array([-2, -3, 5])
# 不等式参数
A_ub = np.array([[-2, 5, -1], [1, 3, 1]])
B_ub = np.array([-10, 12])
# 等式参数
A_eq = np.array([[1, 1, 1]])
B_eq = np.array([7])
# 4.计算结果
res=op.linprog(c, A_ub, B_ub, A_eq, B_eq, bounds=(x1,x2,x3))
print(res)
print("<--------------------------------------->")
# 5.打印结果
x = res.x
print('目标值: \n' + str(-res.fun))
print('最优解为: ')
print('x1 = ' + str(round(x[0],2)))
print('x2 = ' + str(round(x[1],2)))
print('x3 = ' + str(round(x[2],2)))
运行结果
con: array([1.80714554e-09])
fun: -14.571428565645032
message: 'Optimization terminated successfully.'
nit: 5
slack: array([-2.24602559e-10, 3.85714286e+00])
status: 0
success: True
x: array([6.42857143e+00, 5.71428571e-01, 2.35900788e-10])
<--------------------------------------->
目标值:
14.571428565645032
最优解为:
x1 = 6.43
x2 = 0.57
x3 = 0.0
非线性规划
示例文件
# 1.导入相关库
import numpy as np
from scipy.optimize import minimize
# 2.定义非线性函数
def objective(x):
return x[0] ** 2 + x[1]**2 + x[2]**2 +8
def constraint1(x):
return x[0] ** 2 - x[1] + x[2]**2
def constraint2(x):
return -(x[0] + x[1]**2 + x[2]**2-20)
def constraint3(x):
return -x[0] - x[1]**2 + 2
def constraint4(x):
return x[1] + 2*x[2]**2 -3
con1 = {'type': 'ineq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3}
con4 = {'type': 'eq', 'fun': constraint4}
cons = ([con1, con2, con3,con4])
# 3.给出变量范围
b = (0, None)
bnds = (b, b ,b)
# 4.计算结果
x0=np.array([0, 0, 0])
solution=minimize(objective, x0, method='SLSQP', bounds=bnds, constraints=cons)
print(solution)
print("<--------------------------------------->")
# 5.打印结果
x = solution.x
print('目标值: \n' + str(solution.fun))
print('最优解为')
print('x1 = ' + str(round(x[0],2)))
print('x2 = ' + str(round(x[1],2)))
print('x3 = ' + str(round(x[2],2)))
运行结果
fun: 10.651091840572583
jac: array([1.10433471, 2.40651834, 1.89564812])
message: 'Optimization terminated successfully'
nfev: 71
nit: 15
njev: 15
status: 0
success: True
x: array([0.55216734, 1.20325918, 0.94782404])
<--------------------------------------->
目标值:
10.651091840572583
最优解为
x1 = 0.55
x2 = 1.2
x3 = 0.95
735

被折叠的 条评论
为什么被折叠?



