# dot products

John Lenton john at grulic.org.ar
Mon Dec 20 17:26:41 CET 2004

```On Sun, Dec 19, 2004 at 03:04:15AM -0800, Rahul 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

some numbers to confirm my previous reply:

1
zip: 0.00115 (1.00)
range: 0.00108 (0.94)
array: 0.00075 (0.65)
10
zip: 0.00306 (1.00)
range: 0.00288 (0.94)
array: 0.00074 (0.24)
100
zip: 0.02195 (1.00)
range: 0.02035 (0.93)
array: 0.00079 (0.04)
1000
zip: 0.21016 (1.00)
range: 0.19930 (0.95)
array: 0.00130 (0.01)
10000
zip: 4.98902 (1.00)
range: 2.70843 (0.54)
array: 0.01405 (0.00)

(the integers are the number of elements in a random array of floats;
'zip' refers to

sum([x*y for (x,y) in zip(a,b)])

'range', to

sum([a[i]*b[i] for i in range(len(a))])

and 'array' makes a and b Numeric's 'array' objects, with atlas
tuned for the system's processor (in this case a pentium3)). The code
in this case is simply

Numeric.dot(a, b)

The advantage of atlas on systems with sse2 should be even greater.

--
John Lenton (john at grulic.org.ar) -- Random fortune:
El deseo nos fuerza a amar lo que nos hará sufrir.
-- Marcel Proust. (1871-1922) Escritor francÃ©s.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20041220/93153f47/attachment.sig>
```