我在优化包含循环的函数时遇到问题。我从lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]
浮点数和间隔 `(0,k*0.0025),(0.005,k*0.005),(0.005,k*0.0125) 开始,其中上边界取决于。因此,根据列表的浮点数属于哪个区间,我将值 k*0.005、k*0.01、k*0.025 和 k*0.05 之一分配给函数,这些值也取决于 k。
我想最小化,使得或k
值的总和(新标量函数)等于 0.32。assign(k)
sum(assign(k))
我使用scipy.optimize
程序来做到这一点。我的约束是constraint=sum(assign(k))-0.32
和目标函数 iz fun(k)=k
。所以,我最小化k
以满足约束。
import scipy
from scipy.optimize import minimize
lista=[0.002,0.006,0.003,0.02,0.008,0.006,0.05]
def assign(k):
return list(map(lambda x:(k*0.005 if x in np.arange(0,k*0.0025,0.001)
else k*0.01 if x in np.arange(0.0025,k*0.005,0.001) else k*0.025 if x in
np.arange(0.005,k*0.0125,0.001) else k*0.05), lista))
def constraint(k):
return sum(assign(k))-0.32
def fun(k):
return k
k0=0
bnds=[(0,10)]
cons={'type':'eq','fun':constraint}
res=minimize(fun,k0,bounds=bnds,method='SLSQP',constraints=cons,options={'maxiter':2000})
print(res)
我得到k=1.1999这是一个奇怪的结果,它不满足约束。应该是2
因为sum(assign(2))=0.52
。我还收到一条错误消息:
message: 'Iteration limit exceeded'
有谁知道如何克服这个限制?先感谢您!