【问题标题】:TypeError: only size-1 arrays can be converted to Python scalars when using trapz methodTypeError:使用 trapz 方法时,只能将 size-1 数组转换为 Python 标量
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-12-29
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多