使用Python中的複合梯形規則沿軸0積分
要使用複合梯形規則沿給定軸積分,請使用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 = 0))
示例
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 = 0))
輸出
Our Array... [[0 1 2] [3 4 5] [6 7 8]] Dimensions of our Array... 2 Datatype of our Array object... int64 Result (trapz)... [ 6. 8. 10.]
廣告