5.4

import numpy as np

import math

from scipy.optimize import minimize, Bounds

def func(x):
return sum(math.sqrt(x[i]) for i in range(100))

def con(x):
return 1000 - np.sum(x[i] * (101 - i + 1) for i in range(100))

con1 = {'type': 'ineq', 'fun': lambda x: 10 - x[0]}

con2 = {'type': 'ineq', 'fun': lambda x: 20 - x[0] - 2 * x[1]}

con3 = {'type': 'ineq', 'fun': lambda x: 30 - x[0] - x[1] * 2 - x[2] * 3}

con4 = {'type': 'ineq', 'fun': lambda x: 40 - x[0] - x[1] * 2 - x[2] * 3 - x[3] * 4}

con5 = {'type': 'ineq', 'fun': con}

cons = [con1, con2, con3, con4, con5]

bounds = Bounds([0] * 100, np.inf * 100)

res = minimize(func, np.random.randn(100), constraints=cons, bounds=bounds)

print(res.x)

print(res.fun)

posted @ 2024-10-15 11:34  qi11  阅读(2)  评论(0编辑  收藏  举报