배열의 행렬식(determinant)에서 부호(sign)와 자연로그(natural logarithm)를 동시에 계산하려면 Python의 numpy.linalg.slogdet() 메서드를 사용하면 됩니다. 첫 번째 매개변수인 s는 입력 배열을 의미하며, 반드시 정방형(square) 2차원 배열이어야 합니다.
numpy.linalg.slogdet() 메서드의 반환값
이 메서드는 두 가지 값을 반환합니다.
- sign: 행렬식의 부호를 나타내는 숫자입니다. 실수 행렬의 경우
1,0,-1중 하나이며, 복소수 행렬의 경우 절댓값이 1인 복소수 또는 0입니다. - logdet: 행렬식 절댓값의 자연로그입니다. 행렬식이 0이면 sign은
0, logdet은-Inf가 됩니다.
모든 경우에 다음 관계식이 성립합니다.
determinant = sign * np.exp(logdet)
행렬식 값 자체가 매우 크거나 작아 오버플로우·언더플로우가 발생할 수 있는 상황에서 이 메서드를 활용하면 수치적으로 안정적인 계산이 가능합니다.
단계별 구현 방법
1단계: 필요한 라이브러리 임포트
import numpy as np
2단계: 배열 생성
arr = np.array([[ 1, 2], [ 3, 4]])
3단계: 배열 속성 확인
생성한 배열의 내용, 차원 수, 데이터 타입, 형태(shape)를 확인합니다.
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단계: 일반적인 방법으로 행렬식 계산
선형 대수에서 배열의 행렬식은 np.linalg.det()로 구할 수 있습니다.
print("\nDeterminant...\n",np.linalg.det(arr))5단계: slogdet()으로 부호와 자연로그 계산
numpy.linalg.slogdet() 메서드를 호출하여 행렬식의 부호와 자연로그를 함께 얻습니다.
(sign, logdet) = np.linalg.slogdet(arr)
print("\nResult....\n",(sign, logdet))전체 예제 코드
import numpy as np
# Create an array
arr = np.array([[ 1, 2],
[ 3, 4]])
# 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)
# The determinant of an array in linear algebra
print("\nDeterminant...\n",np.linalg.det(arr))
# Compute the sign and natural logarithm of the determinant
(sign, logdet) = np.linalg.slogdet(arr)
print("\nResult....\n",(sign, logdet))실행 결과
Our Array... [[1 2] [3 4]] Dimensions of our Array... 2 Datatype of our Array object... int64 Shape of our Array object... (2, 2) Determinant... -2.0000000000000004 Result.... (-1.0, 0.6931471805599455)
결과 해석
실행 결과를 보면 np.linalg.det()로 계산한 행렬식은 약 -2.0입니다. 한편 slogdet()의 결과는 (-1.0, 0.6931471805599455)로, 부호가 -1이고 logdet이 ln(2) ≈ 0.6931임을 알 수 있습니다. 검증해 보면 -1 × e^0.6931 = -2이므로, determinant = sign × exp(logdet) 관계가 정확히 성립하는 것을 확인할 수 있습니다.