dot products
Raymond Hettinger
vze4rx4y at verizon.net
Tue Dec 21 03:41:52 CET 2004
[Rahul].
> > I want to compute dot product of two vectors stored as lists a and b.a
> > and b are of the same length.
> >
> > one simple way is
> > sum(a[i]*b[i] for i in range(len(a)))
> >
> > another simple way is
> > ans=0.0
> > for i in range(len(a)):
> > ans=ans+a[i]*b[i]
> >
> > But is there any other way which is faster than any of the above.
>
> Yes:
> from itertools import imap
> from operator import mul
> ans = sum(imap(mul, a, b))
Doh! We all missed it.
If your vector length is known in advance (and it often is in some apps), the
simplest and fastest approach is:
a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
C:\pydev>python timedot.py 3
0.32 sec: a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
1.38 sec: sum(a[i]*b[i] for i in xrange(len(a)))
1.32 sec: sum(x*y for x,y in izip(a,b))
1.62 sec: sum(x*y for x,y in zip(a,b))
0.75 sec: sum(imap(mul, a, b))
1.04 sec: sum(map(mul, a, b))
Raymond Hettinger
More information about the Python-list
mailing list