Dot product

Revision as of 07:18, 24 February 2010 by rosettacode>Paddy3118 (New task and python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Create a function/use an in-built function, to compute the wp:Dot product, also known as the scaler product of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors [1, 3, -5] and [4, -2, -1].

Task
Dot product
You are encouraged to solve this task according to the task description, using any language you may know.

To calculate the dot product of two vectors, each vector must be the same length; multiply corresponding terms from each vector then sum the result to produce the answer:

Python

<lang python>def dotp(a,b):

   assert len(a) == len(b), 'Vector sizes must match'
   return sum(aterm * bterm for aterm,bterm in zip(a, b))

if __name__ == '__main__':

   a, b = [1, 3, -5], [4, -2, -1]
   dotp(a,b)
   assert dotp(a,b) == 3</lang>