Python 中計算兩個向量的點積
要返回兩個向量的點積,請在 Python 中使用 numpy.vdot() 方法。vdot(a, b) 函式處理複數的方式與 dot(a, b) 不同。如果第一個引數是複數,則在計算點積時使用第一個引數的複共軛。vdot 處理多維陣列的方式與 dot 不同:它不會執行矩陣乘積,而是首先將輸入引數展平為一維向量。因此,它應該只用於向量。
該方法返回 a 和 b 的點積。根據 a 和 b 的型別,可以是 int、float 或 complex。第一個引數是 a。如果 a 是複數,則在計算點積之前取其複共軛。b 是點積的第二個引數。
步驟
首先,匯入所需的庫:
import numpy as np
使用 array() 方法建立兩個 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)
要在 Python 中返回兩個向量的點積,請使用 numpy.vdot() 方法:
print("\nResult...\n",np.vdot(arr1, arr2))
示例
import numpy as np # Creating two numpy One-Dimensional array using the array() method arr1 = np.array([2+3j,5+6j]) arr2 = np.array([9+10j,11+12j]) # 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 return the dot product of two vectors, use the numpy.vdot() method in Python. 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)
廣告