使用 Python 中的複合梯形規則沿軸 1 進行積分


要沿給定軸使用複合梯形規則進行積分,請使用 numpy.trapz() 方法。如果提供了 x,則積分會沿著其元素的順序進行 - 它們不會被排序。該方法返回 'y'(n 維陣列)沿單個軸的定積分,該積分由梯形規則近似。如果 'y' 是一個一維陣列,則結果為浮點數。如果 'n' 大於 1,則結果為 'n-1' 維陣列。

第一個引數 y 是要積分的輸入陣列。第二個引數 x 是對應於 y 值的取樣點。如果 x 為 None,則假設取樣點均勻分佈,間隔為 dx。預設值為 None。第三個引數 dx 是當 x 為 None 時取樣點之間的間距。預設值為 1。第四個引數 axis 是要沿其積分的軸。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 arange() 方法建立 NumPy 陣列。我們添加了整數型別的元素 -

arr = np.arange(9).reshape(3, 3)

顯示陣列 -

print("Our Array...\n",arr)

檢查維度 -

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別 -

print("\nDatatype of our Array object...\n",arr.dtype)

要沿給定軸使用複合梯形規則進行積分,請使用 numpy.trapz() 方法 -

print("\nResult (trapz)...\n",np.trapz(arr, axis = 1))

示例

import numpy as np

# Creating a numpy array using the arange() method
# We have added elements of int type
arr = np.arange(9).reshape(3, 3)

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# To integrate along the given axis using the composite trapezoidal rule, use the numpy.trapz() method
print("\nResult (trapz)...\n",np.trapz(arr, axis = 1))

輸出

Our Array...
[[0 1 2]
[3 4 5]
[6 7 8]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Result (trapz)...
[ 2. 8. 14.]

更新於: 2022 年 2 月 25 日

241 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告