将两个 numpy 数组相乘的有效方法是什么?例如,给定
A = [1, 2, 3, 4]
B = [2, 3, 5, 7]
我想计算A和B的点积,即
A.B/|A||B| = (1*2 + 2*3 + .. 4*7)/sqrt(1^2 + 2^2... +4^2) * sqrt(.....)
我怎样才能高效快速地做到这一点?
请您参考如下方法:
如果您使用的是 numpy,numpy.dot会为你做这份工作
numpy.dot(A,B)
51
向量的最快范数是
n = math.sqrt(numpy.dot(A,A.conj()))
这是与其他方法的比较
>>> t1=timeit.Timer("n = math.sqrt(numpy.dot(A,A.conj()))","from __main__ import A,math,numpy")
>>> t2=timeit.Timer("n = math.sqrt(sum(abs(A)**2))","from __main__ import A,math")
>>> t3=timeit.Timer("numpy.linalg.norm(A)","from __main__ import A,numpy")
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
2.82 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
13.16 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t3.timeit(number=100000)/100000)
15.68 usec/pass
>>>
