Python에서 1차원 벡터의 내적(dot product)을 반환하려면 numpy.vdot() 메서드를 사용하면 됩니다. vdot(a, b) 함수는 dot(a, b)와 달리 복소수를 특별한 방식으로 처리합니다. 첫 번째 인자가 복소수인 경우, 내적 계산 시 첫 번째 인자의 복소켤레(complex conjugate)를 사용합니다.
또한 vdot()은 다차원 배열을 다루는 방식에서도 dot()과 차이가 있습니다. 행렬 곱(matrix product)을 수행하지 않고, 입력 인자를 먼저 1차원 벡터로 평탄화(flatten)한 뒤 내적을 계산합니다. 따라서 이 함수는 벡터에만 사용하는 것이 좋습니다.
이 메서드는 a와 b의 내적을 반환하며, 반환값의 자료형은 a와 b의 타입에 따라 int, float 또는 complex가 될 수 있습니다. 첫 번째 매개변수는 a이며, a가 복소수라면 내적 계산 전에 복소켤레가 취해집니다. 두 번째 매개변수 b는 내적 계산에 사용되는 값입니다.
단계별 진행
먼저 필요한 라이브러리를 임포트합니다 −
import numpy as np
array() 메서드를 사용해 두 개의 1차원 NumPy 배열을 생성합니다 −
arr1 = np.array([2+3j,5+6j]) arr2 = np.array([9+10j,11+12j])
배열을 화면에 출력합니다 −
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)두 배열의 차원(dimension)을 확인합니다 −
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)두 배열의 형태(shape)를 확인합니다 −
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)numpy.vdot() 메서드를 사용하여 1차원 벡터의 내적을 구합니다 −
print("\nResult...\n",np.vdot(arr1, arr2))전체 예제 코드
import numpy as np
# array() 메서드를 사용해 두 개의 1차원 NumPy 배열 생성
arr1 = np.array([2+3j,5+6j])
arr2 = np.array([9+10j,11+12j])
# 배열 출력
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.vdot() 메서드로 1차원 벡터의 내적 계산
print("\nResult...\n",np.vdot(arr1, arr2))실행 결과
Array1... [2.+3.j 5.+6.j] Array2... [ 9.+10.j 11.+12.j] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (2,) Shape of Array2... (2,) Result... (175-13j)