类型错误:使用 trapz 方法时只能将 size-1 数组转换为 Python 标量

问题描述 投票:0回答:1

这是我的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 方法则不行

python numpy scipy typeerror numerical-integration
1个回答
0
投票

正如用户评论的那样,您只能使用具有标量值的数学函数,对于数组,您必须使用 NumPy 库中提供的数学函数。

© www.soinside.com 2019 - 2024. All rights reserved.