Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ทำการ integral ตาม axis ที่กำหนดด้วยกฎ trapezoidal แบบ composite ใน Python


ภาพรวม

ใช้ numpy.trapz() ทำ numerical integration ตาม axis ที่กำหนดด้วย composite trapezoidal rule ถ้าให้ x จะ integrate ตามลำดับ elements (ไม่ sort) คืนค่า definite integral

  • y เป็น 1-D → คืน float
  • y เป็น n-D (n>1) → คืน (n-1)-D array

พารามิเตอร์

  • y: อาร์เรย์อินพุทที่จะ integrate
  • x (optional): sample points ตรงกับ y (default None = equally spaced dx)
  • dx (optional): spacing เมื่อ x=None (default 1)
  • axis (optional): axis ที่ integrate

ขั้นตอนการทำงาน

1. นำเข้า NumPy

import numpy as np

2. สร้างอาร์เรย์ 3x3

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

3. แสดงข้อมูลอาร์เรย์

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

4. Integrate ตาม axis=0

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

ตัวอย่างโค้ดเต็ม

import numpy as np
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)
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.]

คำอธิบาย: Integrate แต่ละ column (axis=0) ด้วย trapezoidal rule: column 0: (0+3)/2 + (3+6)/2 = 1.5 + 4.5 = 6, column 1: 8, column 2: 10