Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 선형 행렬 방정식 또는 선형 스칼라 방정식 시스템 풀기

<시간/>

선형 행렬 방정식을 풀려면 Python에서 numpy.linalg.solve() 메서드를 사용합니다. 이 방법은 잘 결정된, 즉 전체 순위 선형 행렬 방정식 ax =b의 "정확한" 해 x를 계산합니다. 시스템 x =b에 대한 솔루션을 반환합니다. 반환된 모양은 b와 동일합니다. 첫 번째 매개변수 a는 계수 행렬입니다. 두 번째 매개변수 b는 Ordinate 또는 "종속 변수" 값입니다.

단계

먼저 필요한 라이브러리를 가져옵니다. -

import numpy as np

array() 메서드를 사용하여 두 개의 2D numpy 배열 만들기. 연립방정식 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))
의 .linalg.solve() 메서드

출력

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.]