Is this answer correct: https://stackoverflow.com/a/39662710/1175080 ?
Quoting that answer.
In Python 3.5, there is a new operator for the dot product, so you can write a= A @ B instead of a= numpy.dot(A,B)
It does not seem to work for me.
$ python3
Python 3.6.1 (default, Apr 4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a @ b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for @: 'list' and 'list'
>>>
But the linked answer has received 6 upvotes, so I must be missing something. Can you provide a complete example that shows how to use the @
operator to calculate a dot product?
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 .
We can calculate the dot product of lists of equal length using the zip() function and the sum() function. The zip function returns a zip object by combining elements in a sequence of tuples from both iterables. On the other hand, the sum function returns the sum of items in iterables such as lists.
To return the dot product of two vectors, use the numpy. vdot() method in Python.
See what's new in Python 3.5, section matrix mult (PEP 465):
PEP 465 adds the
@
infix operator for matrix multiplication. Currently, no builtin Python types implement the new operator, however, it can be implemented by defining__matmul__()
,__rmatmul__()
, and__imatmul__()
for regular, reflected, and in-place matrix multiplication. The semantics of these methods is similar to that of methods defining other infix arithmetic operators.
So, you would have to implement those methods yourself.
Or, use numpy>=1.10
which already has support for the new operator:
>>> import numpy
>>> x = numpy.ones(3)
>>> m = numpy.eye(3)
>>> x @ m
array([ 1., 1., 1.])
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