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.inf100)
res=minimize(func,np.random.randn(100),constraints=cons,bounds=bounds)
print(res.x)
print(res.fun)
import numpy as np
from scipy.optimize import minimize
def objective(x):
return - (2 * x[0] + 3 * x[0]2 + 3 * x[1] + x[1]2 + x[2])
def con1(x):
return 10 - (x[0] + 2 * x[0]2 + x[1] + 2 * x[1]2 + x[2])
def con2(x):
return 50 - (x[0] + x[0]2 + x[1] + x[1]2 - x[2])
def con3(x):
return 40 - (2 * x[0] + x[0]2 + 2 * x[1] + x[2])
def con4(x):
return x[0] + 2 * x[1] - 1
def con5(x):
return x[0]
def con6(x):
return x[0]2 + x[2] - 2
cons = ({'type': 'ineq', 'fun': con1},
{'type': 'ineq', 'fun': con2},
{'type': 'ineq', 'fun': con3},
{'type': 'ineq', 'fun': lambda x: -con4(x)},
{'type': 'ineq', 'fun': lambda x: con5(x)},
{'type': 'eq', 'fun': con6})
x0 = np.random.rand(3)
bounds = [(0, None) for _ in range(3)]
solution = minimize(objective, x0, method='SLSQP', bounds=bounds, constraints=cons)
print('Optimal solution:', solution.x)
print('Objective value at optimal solution:', -solution.fun)