在不使用 np.dot 或 Python 中的循环的情况下查找点积



我需要编写一个函数:

  1. 接收 - 两个numpy.array对象
  2. 返回 - 两个输入的浮点积numpy数组

不允许使用:

  1. numpy.dot()
  2. 任何类型的循环

有什么建议吗?

一种可能的解决方案是使用递归

import numpy as np
def multiplier (first_vector, second_vector, size, index, total):
if index < size:
addendum = first_vector[index]*second_vector[index]
total = total + addendum
index = index + 1
# ongoing job
if index < size:
multiplier(first_vector, second_vector, size, index, total)
# job done
else:
print("dot product = " + str(total))

def main():
a = np.array([1.5, 2, 3.7])
b = np.array([3, 4.3, 5])
print(a, b)
i = 0
total_sum = 0
# check needed if the arrays are not hardcoded
if a.size == b.size:
multiplier(a, b, a.size, i, total_sum)
else:
print("impossible dot product for arrays with different size")
if __name__== "__main__":
main()

可能被认为是作弊,但 Python 3.5 添加了一个矩阵乘法运算符,numpy使用它来计算点积而不实际调用np.dot

>>> arr1 = np.array([1,2,3])
>>> arr2 = np.array([3,4,5])
>>> arr1 @ arr2
26

问题解决了!

相关内容

最新更新