返回Python中兩個多維向量的點積


要返回兩個多維向量的點積,請在Python中使用numpy.vdot()方法。vdot(a, b)函式處理複數的方式與dot(a, b)不同。如果第一個引數是複數,則在計算點積時使用第一個引數的複共軛。vdot處理多維陣列的方式與dot不同:它不會執行矩陣乘積,而是首先將輸入引數展平為一維向量。因此,它應該只用於向量。

該方法返回a和b的點積。根據a和b的型別,可以是整數、浮點數或複數。第一個引數是a。如果a是複數,則在計算點積之前取其複共軛。b是點積的第二個引數。

步驟

首先,匯入所需的庫:

import numpy as np

使用array()方法建立兩個NumPy多維陣列:

arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

顯示陣列:

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 Multi-Dimensional array using the array() method
arr1 = np.array([[5, 10],[15, 20]])
arr2 = np.array([[3, 6],[9, 12]])

# 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 multi-dimensional vectors, use the numpy.vdot() method in Python.
print("\nResult...\n",np.vdot(arr1, arr2))

輸出

Array1...
[[ 5 10]
[15 20]]

Array2...
[[ 3 6]
[ 9 12]]

Dimensions of Array1...
2

Dimensions of Array2...
2

Shape of Array1...
(2, 2)

Shape of Array2...
(2, 2)

Result...
450

更新於:2022年3月1日

407 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.