在`integrate.quadrature`中,`max`函数失败。

huangapple go评论72阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2023年2月9日 03:45:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75391007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定