为什么 numpy 不允许数组乘以标量?
Why doesn't numpy allow array multiplication by scalars?
对于 dot
方法,我假设 @
是 shorthand。是什么促使设计决定阻止形状为 ()
的数组乘法?
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
@
是 matmul
的中缀运算符,而不是 dot
(请注意,这两个函数对于 higher-dimensional 数组(高于 2D)是不等价的)。
文档中没有明确说明拒绝标量作为操作数的原因,但动机似乎可能源于 PEP 0465,它最初提议引入 @
作为 [ 的中缀运算符=27=] 3.5。来自 'semantics' 部分:
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"].
对于 dot
方法,我假设 @
是 shorthand。是什么促使设计决定阻止形状为 ()
的数组乘法?
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
@
是 matmul
的中缀运算符,而不是 dot
(请注意,这两个函数对于 higher-dimensional 数组(高于 2D)是不等价的)。
文档中没有明确说明拒绝标量作为操作数的原因,但动机似乎可能源于 PEP 0465,它最初提议引入 @
作为 [ 的中缀运算符=27=] 3.5。来自 'semantics' 部分:
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"].