这是我的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
为什么会这样呢? 使用四元法积分效果很好,但使用 trapz 方法则不行
正如用户评论的那样,您只能使用具有标量值的数学函数,对于数组,您必须使用 NumPy 库中提供的数学函数。