import numpy as np
from scipy.optimize import minimize
def objective(x):
x1, x2, x3 = x
return -(2 * x1 + 3 * x1 ** 2 + 3 * x2 + x2 ** 2 + x3)
# 定义约束条件
def constraint1(x):
x1, x2 = x[:2] # 只取前两个变量x1和x2
return 10 - (x1 + 2 * x1 ** 2 + x2 + 2 * x2 ** 2) # 假设没有x5
def constraint2(x):
x1, x2, x3 = x
return 10 - (x1 + x1 ** 2 + x2 + x2 ** 2 - x3)
def constraint3(x):
x1, x3 = x[:2] # 只取前两个变量x1和x3(注意这里的x是切片,但x3实际上是第三个元素)
return x3 - (x1 ** 2 + x3)
def constraint4(x):
x1, x2 = x[:2] # 只取前两个变量x1和x2
return x1 + 2 * x2 - 1
# 初始猜测值(只包含目标函数和约束中使用的变量)
x0 = [0.5, 0.5, 0.5]
# 定义约束条件的字典
con1 = {'type': 'ineq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
con3 = {'type': 'eq', 'fun': constraint3} # 这是一个等式约束
con4 = {'type': 'ineq', 'fun': constraint4}
cons = [con1, con2, con3, con4]
# 求解优化问题
# 注意:bounds现在只针对x1, x2, x3
solution = minimize(objective, x0, method='SLSQP', constraints=cons,
bounds=[(None, None), (None, None), (None, None)])
# 输出结果
print('Optimal solution:', solution.x)
print('Objective function value at optimal solution:', -solution.fun) # 注意取负值以得到最大化结果
print('学号:3015')
标签:None,return,5.5,solution,x2,x3,x1
From: https://www.cnblogs.com/fzn666/p/18510259