numpy自除的意外行为 [英] Unexpected behavior for numpy self division
问题描述
def f(x):
x=x/5.
return x
def g(x):
x/=5.
return x
x_var = np.arange(5,dtype=np.double)
f(x_var)
print x_var
g(x_var)
print x_var
Output:
[ 0. 1. 2. 3. 4.]
[ 0. 0.2 0.4 0.6 0.8]
这种行为对我来说有点奇怪,我一直以为x / = 5。等于x = x / 5。 。但显然g(x)函数不会使用/ =操作创建新的引用。有人可以为此提供解释吗?
This behavior is a little bit strange to me, I always thought x/=5. was equivalent to x=x/5. . But clearly the g(x) function does not create a new reference with /= operation. Could anyone offer an explanation for this?
推荐答案
我一直认为x / = 5。等价于x = x / 5
I always thought x/=5. was equivalent to x=x/5
就是这样,除非该类覆盖了 __ idiv __
运算符,就像 numpy.ndarray
一样。
numpy.ndarray
会覆盖它以就地修改数组,这很好,因为当不需要复制时,它避免了创建数组的新副本。如您所料,它还会覆盖其余的 __ i * __
运算符。
It is, unless the class overrides the __idiv__
operator, like numpy.ndarray
does.
numpy.ndarray
overrides it to modify the array in-place, which is good because it avoids creating a new copy of the array, when copying is not required. As you can guess, it also overrides the rest of the __i*__
operators.
这篇关于numpy自除的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!