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

คำนวณ determinant สำหรับสแต็กของเมทริกซ์ในพีชคณิตเชิงเส้นด้วย Python


ภาพรวม

ในการคำนวณ determinant (ค่าดีเทอร์มิแนนต์) สำหรับสแต็กของเมทริกซ์หลายตัวพร้อมกันในพีชคณิตเชิงเส้น สามารถใช้ฟังก์ชัน np.linalg.det() ของไลบรารี NumPy ใน Python ฟังก์ชันนี้รับพารามิเตอร์ a ซึ่งเป็นอาร์เรย์อินพุตที่ต้องการคำนวณ determinant และคืนค่า determinant ของแต่ละเมทริกซ์ในสแต็ก

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

1. นำเข้าไลบรารีที่จำเป็น

import numpy as np

2. สร้างอาร์เรย์ 3 มิติ (สแต็กของเมทริกซ์ 2x2 จำนวน 3 ตัว)

arr = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])

3. แสดงอาร์เรย์ที่สร้างขึ้น

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

4. ตรวจสอบมิติของอาร์เรย์

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

5. ตรวจสอบชนิดข้อมูล

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

6. ตรวจสอบรูปทรง (shape) ของอาร์เรย์

print("\nShape of our Array object...\n", arr.shape)

7. คำนวณ determinant ของทุกเมทริกซ์ในสแต็ก

print("\nResult (determinant)...\n", np.linalg.det(arr))

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

import numpy as np
# Create an array
arr = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
# 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)
# Get the Shape
print("\nShape of our Array object...\n", arr.shape)
# Compute determinant for stack of matrices
print("\nResult (determinant)...\n", np.linalg.det(arr))

ผลลัพธ์ที่คาดหวัง

Our Array...
[[[1 2]
  [3 4]]
 [[1 2]
  [2 1]]
 [[1 3]
  [3 1]]]
Dimensions of our Array...
3
Datatype of our Array object...
int64
Shape of our Array object...
(3, 2, 2)
Result (determinant)...
[-2. -3. -8.]

หมายเหตุ: ผลลัพธ์เป็นอาร์เรย์ 1 มิติที่มีค่า determinant ของแต่ละเมทริกซ์ตามลำดับในสแต็ก สำหรับเมทริกซ์ 2x2 สูตรคือ ad - bc ซึ่งตรงกับผลลัพธ์ที่ได้: -2, -3, -8