📜  在Python中使用 NumPy 计算一维数组的向量内积

📅  最后修改于: 2022-05-13 01:54:20.184000             🧑  作者: Mango

在Python中使用 NumPy 计算一维数组的向量内积

Python有一个名为 NumPy 的流行包,用于对一维和多维数组执行复杂的计算。要找到两个数组的内积,我们可以使用 NumPy 包的 inner()函数。

示例 1:

Python3
# Importing library
import numpy as np
  
# Creating two 1-D arrays
array1 = np.array([6,2])
array2 = np.array([2,5])
  
print("Original 1-D arrays:")
print(array1)
print(array2)
  
# Output
print("Inner Product of the two array is:")
result = np.inner(array1, array2)
print(result)


Python3
# Importing library
import numpy as np
  
# Creating two 1-D arrays
array1 = np.array([1,3,5])
array2 = np.array([0,1,5])
  
print("Original 1-D arrays:")
print(array1)
print(array2)
  
# Output
print("Inner Product of the two array is:")
result = np.inner(array1, array2)
print(result)


Python3
# Importing library
import numpy as np
  
# Creating two 1-D arrays
array1 = np.array([1,2,2,8])
array2 = np.array([2,1,0,6])
  
print("Original 1-D arrays:")
print(array1)
print(array2)
  
# Output
print("Inner Product of the two array is:")
result = np.inner(array1, array2)
print(result)


输出:

Original 1-D arrays:
[6 2]
[2 5]
Inner Product of the two array is:
22

示例 2:

Python3

# Importing library
import numpy as np
  
# Creating two 1-D arrays
array1 = np.array([1,3,5])
array2 = np.array([0,1,5])
  
print("Original 1-D arrays:")
print(array1)
print(array2)
  
# Output
print("Inner Product of the two array is:")
result = np.inner(array1, array2)
print(result)

输出:

Original 1-D arrays:
[1 3 5]
[0 1 5]
Inner Product of the two array is:
28

示例 3:

Python3

# Importing library
import numpy as np
  
# Creating two 1-D arrays
array1 = np.array([1,2,2,8])
array2 = np.array([2,1,0,6])
  
print("Original 1-D arrays:")
print(array1)
print(array2)
  
# Output
print("Inner Product of the two array is:")
result = np.inner(array1, array2)
print(result)

输出:

Original 1-D arrays:
[1 2 2 8]
[2 1 0 6]
Inner Product of the two array is:
52