ในการแก้สมการเมทริกซ์เชิงเส้น ให้ใช้เมธอด numpy.linalg.solve() ใน Python วิธีการคำนวณวิธีแก้ปัญหา "แน่นอน", x, ของที่กำหนดไว้อย่างดี, นั่นคือ, เต็มยศ, สมการเมทริกซ์เชิงเส้น ax =b คืนค่าโซลูชันให้กับระบบ a x =b รูปร่างที่ส่งคืนจะเหมือนกับ b พารามิเตอร์ที่ 1 a คือเมทริกซ์สัมประสิทธิ์ พารามิเตอร์ตัวที่ 2 b คือค่า Ordinate หรือ “ตัวแปรตาม”
ขั้นตอน
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import numpy as np
การสร้างอาร์เรย์ numpy 2D สองชุดโดยใช้เมธอด array() พิจารณาระบบสมการ x0 + 2 * x1 =1 และ 3 * x0 + 5 * x1 =2 −
arr1 = np.array([[1, 2], [3, 5]]) arr2 = np.array([1, 2])
แสดงอาร์เรย์ -
print("Array1...\n",arr1)
print("\nArray2...\n",arr2) ตรวจสอบขนาดของอาร์เรย์ทั้งสอง -
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim) ตรวจสอบรูปร่างของอาร์เรย์ทั้งสอง -
Print(“\nShape of Array1…\n”,arr1.shape)
print("\nShape of Array2...\n",arr2.shape) ในการแก้สมการเมทริกซ์เชิงเส้น ใช้เมธอด numpy.linalg.solve() -
print("\nResult...\n",np.linalg.solve(arr1, arr2)) ตัวอย่าง
import numpy as np
# Creating two 2D numpy arrays using the array() method
# Consider the system of equations x0 + 2 * x1 = 1 and 3 * x0 + 5 * x1 = 2
arr1 = np.array([[1, 2], [3, 5]])
arr2 = np.array([1, 2])
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To solve a linear matrix equation, use the numpy.linalg.solve() method in Python.
print("\nResult...\n",np.linalg.solve(arr1, arr2)) ผลลัพธ์
Array1... [[1 2] [3 5]] Array2... [1 2] Dimensions of Array1... 2 Dimensions of Array2... 1 Shape of Array1... (2, 2) Shape of Array2... (2,) Result... [-1. 1.]