5.4

2023310143015發表於2024-10-28

  • 程式碼
點選檢視程式碼
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('學號:3015')

相關文章