Dot product: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
mNo edit summary
Line 1: Line 1:
{{task}}
{{task}}
Create a function/use an in-built function, to compute the [[wp:Dot product|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 <code>[1, 3, -5]</code> and <code>[4, -2, -1]</code>.
Create a function/use an in-built function, to compute the [[wp:Dot product|dot product]], also known as the '''scaler product''' of two vectors. <br>If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors <code>[1, 3, -5]</code> and <code>[4, -2, -1]</code>.


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:
To calculate the dot product of two vectors, each vector must be the same length; multiply corresponding terms from each vector then sum the results to produce the answer:


=={{header|Python}}==
=={{header|Python}}==

Revision as of 07:20, 24 February 2010

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

Create a function/use an in-built function, to compute the 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].

To calculate the dot product of two vectors, each vector must be the same length; multiply corresponding terms from each vector then sum the results 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>