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

Python에서 계수의 2D 배열을 활용해 점 (x, y, z)에서 3D 르장드르 급수 평가하기

Python NumPy에서 polynomial.legendre.legval3d() 메서드를 사용하면 점 (x, y, z)에서 3D 르장드르(Legendre) 급수를 평가할 수 있습니다. 이 메서드는 x, y, z에 대응하는 값들의 조합으로 이루어진 점들에서 다차원 다항식의 값을 반환합니다.

계수 배열 c가 3차원 미만이라면, 형태(shape)를 3차원으로 맞추기 위해 1이 암묵적으로 추가됩니다. 결과의 형태는 c.shape[3:] + x.shape가 됩니다.

매개변수 설명

첫 번째 매개변수: x, y, z
3차원 급수는 점 (x, y, z)에서 평가되며, 이때 x, y, z는 반드시 동일한 형태를 가져야 합니다. 만약 x, y, z 중 하나라도 리스트(list)나 튜플(tuple)이면 먼저 ndarray로 변환되고, 이미 ndarray인 경우에는 그대로 사용됩니다. ndarray가 아닌 값은 스칼라(scalar)로 취급됩니다.

두 번째 매개변수: c
계수 배열로, 다중 차수(multidegree) i, j, k에 해당하는 항의 계수가 c[i, j, k]에 저장되도록 정렬되어 있습니다. c의 차원이 3보다 큰 경우, 나머지 인덱스들은 여러 개의 계수 집합을 나타냅니다.

단계별 구현 방법

먼저 필요한 라이브러리를 임포트합니다.

import numpy as np
from numpy.polynomial import legendre as L

계수로 사용할 2D 배열을 생성합니다.

c = np.arange(4).reshape(2,2)

배열을 출력해 확인합니다.

print("Our Array...\n",c)

배열의 차원을 확인합니다.

print("\nDimensions of our Array...\n",c.ndim)

배열의 데이터 타입을 확인합니다.

print("\nDatatype of our Array object...\n",c.dtype)

배열의 형태(shape)를 확인합니다.

print("\nShape of our Array object...\n",c.shape)

점 (x, y, z)에서 3D 르장드르 급수를 평가하기 위해 polynomial.legendre.legval3d() 메서드를 호출합니다.

print("\nResult...\n",L.legval3d([1,2],[1,2],[1,2],c))

전체 예제 코드

import numpy as np
from numpy.polynomial import legendre as L

# 계수로 사용할 2D 배열 생성
c = np.arange(4).reshape(2,2)

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

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

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

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

# legval3d() 메서드로 점 (x, y, z)에서 3D 르장드르 급수 평가
print("\nResult...\n",L.legval3d([1,2],[1,2],[1,2],c))

실행 결과

Our Array...
    [[0 1]
    [2 3]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

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

Result...
    [24. 42.]

위 실행 결과에서 볼 수 있듯이, 2×2 형태의 계수 배열과 좌표 [1, 2]를 입력했을 때 legval3d() 메서드는 각 점에서 계산된 3D 르장드르 급수의 값인 [24., 42.]를 반환합니다. 참고로 계수 배열이 2차원이므로 내부적으로 자동으로 3차원으로 확장되어 처리됩니다.