习题5

学号后四位3026 1班
5.4
import numpy as np
from scipy.optimize import minimize
obj=lambda x:-sum(np.sqrt(x))
a=np.zeros((5,100))
for i in range(4):
for j in range(i+1):
a[i,j]=j+1
a[4,:]=101-np.arange(1,101)
b=np.hstack([np.arange(10,49,10),1000])
cons={'type':'ineq','fun':lambda x:b-a@x}
bd=tuple(zip([0]100,[1000]100))
res=minimize(obj, np.random.rand(100),constraints=cons,bounds=bd)
print(res)

5.5
from scipy.optimize import minimize
import numpy as np
obj=lambda x:-(2x[0]+3x[0]2+3x[1]+x[1]2+x[2])
def constr(x):
x1,x2,x3=x
return [10-x1-2x1**2--x2-2x22-x3,
50-x1-x12-x2-x22+x3,
40-2
x1-x12-2x2-x3,x1+2x2-1]
con1={'type':'ineq','fun':constr}
con2={'type':'eq','fun':lambda x:x[0]**2+x[2]-2}
con=[con1,con2]
bd=[(0,None)];bd2=list(zip([None]2,[None]2))
bd.extend(bd2)
res=minimize(obj, np.random.rand(3),constraints=con,bounds=bd)
print(res)

学号后四位 3026

posted on 2024-10-27 22:56  三元最爱  阅读(2)  评论(0编辑  收藏  举报