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]-2x[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]
x0 = np.zeros(100)
bnds = [(0, None) for _ in range(100)]
res=minimize(func,x0,constraints=cons,bounds=bnds)
def negative_func(x):
return -func(x)
res = minimize(negative_func, x0, constraints=cons, bounds=bnds)
max_func_value = -res.fun
print(res.x)
print(max_func_value)
3022

3022
浙公网安备 33010602011771号