【发布时间】:2021-01-07 06:44:57
【问题描述】:
这是我的python代码
import numpy as np
from scipy.integrate import quad, trapz, simps
import math
def f(x):
return math.exp(-(x**2/2))/math.sqrt(2*math.pi)
result, error = quad(f, 0, np.inf)
print("{:f} {:g}".format(result, error))
x = np.arange(0, 99999, 0.001)
fun = f(x)
res1 = trapz(fun, x)
print(res1)
我得到了这个错误:
... line 6, in f
return math.exp(-(x**2/2))/math.sqrt(2*math.pi)
TypeError: only size-1 arrays can be converted to Python scalars
为什么会这样? 使用 quad 方法的集成效果很好,但使用 trapz 方法效果不佳
【问题讨论】:
-
math函数仅适用于标量值,不适用于数组。如果x是一个数组,则使用np.exp(x)。
标签: python numpy typeerror integration quad