Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python NumPy polyvander()로 복소수 점 배열의 Vandermonde 행렬 생성하기

Python NumPy에서 polynomial.polyvander() 함수를 사용하면 지정된 차수의 Vandermonde 행렬을 손쉽게 생성할 수 있습니다. 이 메서드는 Vandermonde 행렬을 반환하며, 반환되는 행렬의 형태(shape)는 x.shape + (deg + 1,)입니다. 여기서 마지막 인덱스는 x의 거듭제곱을 나타냅니다. 데이터 타입(dtype)은 변환된 x와 동일하게 적용됩니다.

주요 매개변수

  • a: 점(point)들의 배열입니다. 요소 중 하나라도 복소수가 포함되어 있으면 dtype은 complex128로, 그렇지 않으면 float64로 변환됩니다. 입력이 스칼라인 경우 자동으로 1차원 배열로 변환됩니다.
  • deg: 생성할 결과 행렬의 차수를 지정합니다.

구현 단계

1단계: 필요한 라이브러리 임포트

import numpy as np
from numpy.polynomial.polynomial import polyvander

2단계: 복소수 배열 생성

x = np.array([-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j])

3단계: 배열 출력 및 속성 확인

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

4단계: Vandermonde 행렬 생성

polyvander() 함수에 배열과 원하는 차수(예: 2)를 전달하여 Vandermonde 행렬을 생성합니다.

print("\nResult...\n",polyvander(x, 2))

전체 예제 코드

import numpy as np
from numpy.polynomial.polynomial import polyvander

# 복소수 점 배열 생성
x = np.array([-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j])

# 배열 출력
print("Our Array...\n",x)

# 차원 확인
print("\nDimensions of our Array...\n",x.ndim)

# 데이터 타입 확인
print("\nDatatype of our Array object...\n",x.dtype)

# 형태(shape) 확인
print("\nShape of our Array object...\n",x.shape)

# 차수 2의 Vandermonde 행렬 생성
print("\nResult...\n",polyvander(x, 2))

실행 결과

Our Array...
[-2.+2.j -1.+2.j 0.+2.j 1.+2.j 2.+2.j]

Dimensions of our Array...
1

Datatype of our Array object...
complex128

Shape of our Array object...
(5,)

Result...
[[ 1.+0.j -2.+2.j 0.-8.j]
 [ 1.+0.j -1.+2.j -3.-4.j]
 [ 1.+0.j 0.+2.j -4.+0.j]
 [ 1.+0.j 1.+2.j -3.+4.j]
 [ 1.+0.j 2.+2.j 0.+8.j]]

위 결과를 보면 각 복소수 점 x에 대해 [1, x, x²] 열이 생성된 것을 확인할 수 있습니다. 차수가 2이므로 세 개의 열이 만들어지며, 첫 번째 열은 항상 1, 두 번째 열은 x 값, 세 번째 열은 x² 값으로 구성됩니다. 이러한 Vandermonde 행렬은 다항식 회귀, 최소자승 근사 등 다양한 수치 계산에 활용됩니다.