英文:
max function within integrate.quadrature fails
问题
以下是一个基本的 Python 脚本失败了:
from scipy import integrate
integrate.quadrature(lambda t: max(1,t), -2, 2)[0]
出现了以下错误信息:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
在我看来,integrate.quadrature
命令似乎不喜欢 max
函数,但我不明白为什么。
英文:
The following basic Python script fails:
from scipy import integrate
integrate.quadrature(lambda t: max(1,t), -2, 2)[0]
with the error message:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
It looks to me that the integrate.quadrature
command does not like the max
function but I do not understand why.
答案1
得分: 1
`scipy`没有将标量或1个元素的数组传递给您的函数,因此它需要进行向量化处理:
```python
from scipy import integrate
import numpy as np
integrate.quadrature(lambda t: np.maximum(1, t), -2, 2)[0]
您将收到如下警告:
AccuracyWarning: maxiter (50) exceeded. Latest difference = 6.366377e-04
然而,结果将接近预期值4.5:
4.499480255789206
这是一个参考图表:
t = np.linspace(-2, 2, 100)
plt.plot(t, np.maximum(1, t))
[![enter image description here][1]][1]
<details>
<summary>英文:</summary>
`scipy` is not passing a scalar or 1-element array to your function, so it needs to be vectorized:
from scipy import integrate
import numpy as np
integrate.quadrature(lambda t: np.maximum(1, t), -2, 2)[0]
You will get a warning like
AccuracyWarning: maxiter (50) exceeded. Latest difference = 6.366377e-04
However, the result will be close to the expected value of 4.5:
4.499480255789206
Here is a plot for reference:
t = np.linspace(-2, 2, 100)
plt.plot(t, np.maximum(1, t))
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/WiQvW.png
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论