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

คำนวณ eigenvalues ของเมทริกซ์ complex Hermitian หรือ real symmetric ใน Python


ภาพรวม

ใช้ numpy.linalg.eigvalsh() คำนวณ eigenvalues ของเมทริกซ์ complex Hermitian หรือ real symmetric คืนค่า eigenvalues เรียงจากน้อยไปมาก ตาม multiplicity

พารามิเตอร์

  • a: เมทริกซ์ complex หรือ real ที่ต้องการ eigenvalues
  • UPLO (optional): 'L' (default, lower triangular) หรือ 'U' (upper triangular) ใช้เฉพาะ real part ของ diagonal

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

1. นำเข้าไลบรารี

import numpy as np
from numpy import linalg as LA

2. สร้างเมทริกซ์ 2x2 complex

arr = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])

3. แสดงข้อมูลเมทริกซ์

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

4. คำนวณ eigenvalues

print("\nResult...\n", LA.eigvalsh(arr))

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

from numpy import linalg as LA
import numpy as np
arr = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nShape of our Array object...\n", arr.shape)
print("\nResult...\n", LA.eigvalsh(arr))

ผลลัพธ์

Our Array...
[[5.+2.j 9.-2.j]
 [0.+2.j 2.-1.j]]
Dimensions of our Array...
2
Datatype of our Array object... complex128
Shape of our Array object... (2, 2)
Result...
[1. 6.]

หมายเหตุ: เมทริกซ์ต้องเป็น Hermitian (a = aᴴ) หรือ symmetric (real) ถ้าไม่ใช่ ผลลัพธ์อาจไม่ถูกต้อง ใช้ eigvalsh แทน eigvals สำหรับเมทริกซ์ประเภทนี้ เพื่อประสิทธิภาพและความแม่นยำดียิ่งขึ้น