# dot products

Bengt Richter bokr at oz.net
Mon Dec 20 06:39:41 CET 2004

```On 19 Dec 2004 03:04:15 -0800, "Rahul" <codedivine at gmail.com> wrote:

>HI.
>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. (By
>the way profiling them i found that the second is faster by about 30%.)
>rahul
>
Don't know about the timing, but another way:

>>> import operator
>>> a, b = range(5), range(5,10)
>>> sum(map(operator.mul, a, b))
80

Checking...

>>> class OpShow(object):
...     def __init__(self): self.tot = 0
...     def __call__(self, x, y):
...         prod = x*y
...         self.tot += prod
...         print '%3s * %-3s => %s (tot %s)' %(x, y, prod, self.tot)
...         return prod
...
>>> sum(map(OpShow(), a, b))
0 * 5   => 0 (tot 0)
1 * 6   => 6 (tot 6)
2 * 7   => 14 (tot 20)
3 * 8   => 24 (tot 44)
4 * 9   => 36 (tot 80)
80

Regards,
Bengt Richter

```