Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dot product in python [closed]

Does this Python code actually find the dot product of two vectors?

import operator

vector1 = (2,3,5)
vector2 = (3,4,6)
dotProduct = reduce( operator.add, map( operator.mul, vector1, vector2))
like image 626
user458858 Avatar asked Nov 04 '10 04:11

user458858


People also ask

Is there a dot product function in Python?

Python provides a very efficient method to calculate the dot product of two vectors. By using numpy. dot() method which is available in the NumPy module one can do so.

How do you do dot product in Python?

In Python, one way to calulate the dot product would be taking the sum of a list comprehension performing element-wise multiplication. Alternatively, we can use the np. dot() function. Keeping to the convention of having x and y as column vectors, the dot product is equal to the matrix multiplication xTy x T y .

What is dot in Python?

In Python NumPy dot() function is used to return the dot product of given arrays. It accepts two arrays as arguments and calculates their dot product. It can handle 2-D arrays but considers them as matrix and will perform matrix multiplication.

How do you find the dot product of a list in Python?

Use the numpy. dot() Function to Calculate the Dot Product of Two Arrays or Vectors in Python. Use the sum() Function to Calculate the Dot Product of Two Arrays or Vectors in Python.


1 Answers

Yes it does. Here is another way

>>> sum(map( operator.mul, vector1, vector2))
48

and another that doesn't use operator at all

>>> vector1 = (2,3,5)
>>> vector2 = (3,4,6)
>>> sum(p*q for p,q in zip(vector1, vector2))
48
like image 50
John La Rooy Avatar answered Oct 18 '22 02:10

John La Rooy