习题5.4
- 代码实现
点击查看代码
import numpy as np
from scipy.optimize import minimize
def objective(x):
return -np.sqrt(x[0])
def constraint1(x):
return x[0] - 10
def constraint2(x):
return x[0] + 2 * x[1] - 20
def constraint3(x):
return x[0] + 4 * x[2] - 30 # 修改此处
def constraint4(x):
return x[0] + 2 * x[1] + 3 * x[2] + 4 * x[3] - 40
def constraint5(x):
return (np.sum([(101 - i) for i in range(1, 101)]) * x[0]) - 1000 # 简化计算
x0 = np.array([1, 1, 1, 1]) # 如果 constraint5 只与 x[0] 有关,不需要第五个变量
con1 = {'type': 'ineq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
con3 = {'type': 'ineq', 'fun': constraint3}
con4 = {'type': 'ineq', 'fun': constraint4}
con5 = {'type': 'ineq', 'fun': constraint5} if len(x0) == 5 else None
constraints = [con1, con2, con3, con4] + ([con5] if con5 else [])
bounds = [(0, None) for i in range(len(x0))]
solution = minimize(objective, x0, method='SLSQP', bounds=bounds, constraints=constraints)
print(solution.x)
print(-solution.fun)
print('学号:3014')
2.运行结果