gpt4 book ai didi

python - 为什么 numpy 不允许数组乘以标量?

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:57 25 4
gpt4 key购买 nike

我假设 @dot 方法的简写。是什么促使设计决定阻止形状为 () 的数组乘法?

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(请注意,这两个函数对于高维数组(高于 2D)并不等价)。

文档中没有明确说明拒绝标量作为操作数的原因,但动机似乎可能源于 PEP 0465最初提议引入 @ 作为 Python 3.5 的中缀运算符。来自“语义”部分:

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"].

关于python - 为什么 numpy 不允许数组乘以标量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35010478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com