NumPy trapz()

trapz() 函数使用梯形法则计算给定数组的定积分。它通过一系列梯形来近似输入数组所定义曲线下的面积。

示例

import numpy as np

# create an array of y-coordinates
y = np.array([1, 2, 3, 4, 5])

# compute the definite integral using numpy.trapz()
area = np.trapz(y)

print(area)

# Output: 12

trapz() 语法

trapz() 的语法是

numpy.trapz(y, x = None, dx = 1.0, axis = -1)

trapz() 参数

trapz() 函数接受以下参数

  • y - 包含曲线 y 坐标的输入数组
  • x (可选) - 包含曲线 x 坐标的输入数组
  • dx (可选) - x 坐标之间的间隔
  • axis (可选) - 执行积分的轴

trapz() 返回值

numpy.trapz() 函数使用梯形法则返回输入数组的近似定积分。


示例 1:使用 np.trapz() 计算定积分

import numpy as np

# create an array of y-coordinates
y = np.array([2, 5, 7, 3, 6, 9, 1])

# compute the definite integral using numpy.trapz() area = np.trapz(y)
print("Area under the curve:", area)

输出

Area under the curve: 31.5

在上面的示例中,我们有一个 y 数组,它代表曲线的 y 坐标。

np.trapz() 函数用于计算曲线的定积分,使用梯形法则近似曲线下的面积。

结果面积存储在 area 变量中,然后打印出来,在本例中为 31.5


示例 2:trapz() 中 x 和 dx 参数的使用

import numpy as np

# create an array of y-coordinates
y = np.array([1, 2, 3, 4, 5])

# create an array of x-coordinates
x = np.array([0, 1, 2, 3, 4])

# specify the spacing between x-coordinates
dx = 0.5

# compute the definite integral using numpy.trapz() with optional arguments
area = np.trapz(y, x=x, dx=dx)

print("Area under the curve:", area)

输出

Area under the curve: 12.0

在这里,提供了 x 数组来指定 x 坐标,并使用 dx 参数来指定 x 坐标之间的间隔。

通过提供 xdx 参数,我们可以计算具有不均匀间隔的 x 坐标和特定 x 坐标间隔的定积分。


示例 3:trapz() 与 2-D 数组

axis 参数定义了如何计算 2-D 数组中元素的定积分。

  • 如果 axis = None,则将数组展平并计算展平数组的定积分。
  • 如果 axis = 0,则逐列计算定积分。
  • 如果 axis = 1,则逐行计算定积分。

让我们看一个例子。

import numpy as np

# create a 2-D array
array1 = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# calculate the definite integral of the flattened array result1 = np.trapz(array1.flatten())
print('Definite integral of the flattened array:', result1)
# calculate the definite integral column-wise (axis=0) result2 = np.trapz(array1, axis=0)
print('\nDefinite integrals column-wise (axis=0):') print(result2)
# calculate the definite integral row-wise (axis=1) result3 = np.trapz(array1, axis=1)
print('\nDefinite integrals row-wise (axis=1):') print(result3)

输出

Definite integral of the flattened array: 40.0

Definite integrals column-wise (axis=0):
[ 8. 10. 12.]

Definite integrals row-wise (axis=1):
[ 4. 10. 16.]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战