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))
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With