2024-09-28 22:28:20 发布
网友
我需要优化一个一维函数。我的初始值是20,边界是(0,50)
(0,50)
x0=[20]
bounds=(0,50)
sol1=minimize(f,x0,method="SLSQP",bounds=bounds)
但是,这会产生一个索引器。在
SLSQP Error: the length of bounds is not compatible with that of x0.
我在这里犯了什么错误?在
正如在评论中指出的,你可以把界限放在一个列表中。一个最小的例子如下:
from scipy.optimize import minimize def f(x): return (x - 3) ** 2 x0 = [10] bounds = [(0, 50)] res = minimize(f, x0, method='SLSQP', bounds=bounds)
然后res.x将给出预期的array([3.])。在
res.x
array([3.])
正如@sascha在评论中指出的,对于此类问题,您也可以使用^{}:
只需将上面的导入更改为
和使用
然后res2.x返回3.0
res2.x
3.0
只需将上面的f替换为实际函数。在
f
正如在评论中指出的,你可以把界限放在一个列表中。一个最小的例子如下:
然后
res.x
将给出预期的array([3.])
。在正如@sascha在评论中指出的,对于此类问题,您也可以使用^{} :
只需将上面的导入更改为
^{pr2}$和使用
^{3}$然后
res2.x
返回3.0
只需将上面的
f
替换为实际函数。在相关问题 更多 >
编程相关推荐