不使用查找点积美国运输部或Python中的循环

2024-09-25 08:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个函数:

以两个NumPy数组作为参数 返回一个数字:两个输入向量的浮点点乘 numpy数组和np.总和允许使用函数,不允许美国运输部没有循环

在我的介绍课上,我学到了很多关于在不能使用像美国运输部但这件事让我有些困惑。有什么建议吗?在


Tags: 函数numpy参数np数字数组向量建议
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()

可能考虑过作弊,但是python3.5 added a matrix multiply operator用来计算点积,而不实际调用np.dot

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

问题解决了!在

相关问题 更多 >