我有一个计算成本相对较高的函数,给定一个标量,它返回一个 numpy.array() 对象。当我尝试使用 scipy.integrate.romberg 将此函数与标量参数积分时,我从 scipy 用于确定收敛的条件中得到一个内部错误:
Traceback (most recent call last):
File "wqc.py", line 148, in <module>
H_cycle = (m.pi / wt) * scipy.integrate.romberg(H_if, 0, m.pi / wt)
File "/usr/lib/python2.6/site-packages/scipy/integrate/quadrature.py", line 471, in romberg
while (abs(result - lastresult) > tol) and (i <= divmax):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有什么方法可以一次整合整个数组,还是需要逐个元素整合?我想避免第二种解决方案,因为没有简单的方法来计算仅数组的一个元素。
请您参考如下方法:
问题似乎出在这里:
abs(result - lastresult) > tol
result和 lastresult可能是 numpy.arrays(而不是单个值)。因此,上面的整个表达式正在计算真值的数组,而不是单个 True。/False .因此当你and上述表达式的结果为 (i <= divmax) ,你会得到错误 The truth value of an array with more than one element is ambiguous. . ValueError 的建议是适当的。您应该将真值数组转换为单个真值。
example = numpy.array([True, True, True, False])
example.any()
>>> True
example.all()
>>> False
这将解决问题。
