使用複合梯形法則在Python中進行積分


要沿給定軸使用複合梯形法則進行積分,請使用 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

使用 array() 方法建立一個 numpy 陣列。我們添加了整型元素:

arr = np.array([20, 35, 57, 70, 85, 120])

顯示陣列:

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))

示例

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([20, 35, 57, 70, 85, 120])

# 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))

輸出

Our Array...
[ 20 35 57 70 85 120]

Dimensions of our Array...
1

Datatype of our Array object...
int64

Result (trapz)...
317.0

更新於:2022年2月28日

648 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告