[Numpy-discussion] Resolving the associativity/precedence debate for @

Sturla Molden sturla.molden at gmail.com
Sat Mar 22 22:35:05 EDT 2014


Nathaniel Smith <njs at pobox.com> wrote:

> - There might be some speed argument, if people often write things
> like "Mat @ Mat @ vec"? But no-one has found any evidence that people
> actually do write such things often.

With left associativity, this would be an algorithmic optimization:

   Mat @ (Mat @ vec) 
   Mat @ (Mat @ (Mat @ vec))

On the other hand, this 

    vec.T @ Mat @ Mat

would not need parentheses for optimisation when the associativity is left.


With right associativity, we get the same optimisation problem as well:

   (vec.T @ Mat) @ Mat
   ((vec.T @ Mat) @ Mat) @ Mat

Personally I believe this advice to the novice programmer belongs in the
documentation. If we just include it in the NumPy documentation, it will
not be a problem. Advices about how to optimize numerical expressions
should not be special cases in the syntax, in my opinion. That just makes
the Python language harder to learn. Rather, it is a documentation problem
for NumPy. We should write the NumPy documentation for @ such that the
novice programmer easily understands the computational complexities of
linear algebra operations. The PEP might include this as well, so the
knowledge propagates into the rest of the Python language litterature, not
just the NumPy docs.

By the way, the * operator for np.matrix and Matlab matrices are left
associative as well. This does not produce any problems.


Sturla




More information about the NumPy-Discussion mailing list