Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't numpy allow array multiplication by scalars?

I assumed that @ was shorthand for the dot method. What motivated the design decision to block multiplication by an array with shape ()?

In [6]: a = np.ones((2,1))

In [7]: a.dot(1)
Out[7]:
array([[ 1.],
       [ 1.]])

In [8]: a @ 1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-398cff4c0ec9> in <module>()
----> 1 a @ 1

ValueError: Scalar operands are not allowed, use '*' instead
like image 631
Neil G Avatar asked Mar 18 '26 01:03

Neil G


1 Answers

@ is the infix operator for matmul, not dot (note that the two functions are not equivalent for higher-dimensional arrays (higher than 2D)).

No explicit reason for rejecting scalars as operands is stated in the documentation, but it seems probable that the motivation stems from PEP 0465 which originally proposed the introduction of @ as an infix operator for Python 3.5. From the 'semantics' section:

0d (scalar) inputs raise an error. Scalar * matrix multiplication is a mathematically and algorithmically distinct operation from matrix @ matrix multiplication, and is already covered by the elementwise * operator. Allowing scalar @ matrix would thus both require an unnecessary special case, and violate TOOWTDI ["There's Only One Way To Do It"].

like image 80
Alex Riley Avatar answered Mar 20 '26 13:03

Alex Riley