5.5

2023310143015發表於2024-10-28

點選檢視程式碼
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')

相關文章