负指数的 numpy.power 或 ** 和使用数组时/之间有什么区别?为什么 numpy.power 不像 documentation 中描述的那样按元素行事.
例如使用python 2.7.3:
>>> from __future__ import division
>>> import numpy as np
>>> A = arange(9).reshape(3,3)
>>> A
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
当指数为负时,** 和 numpy.power 似乎没有按元素行事
>>> A**-1
array([[-9223372036854775808, 1, 0],
[ 0, 0, 0],
[ 0, 0, 0]])
>>> np.power(A, -1)
array([[-9223372036854775808, 1, 0],
[ 0, 0, 0],
[ 0, 0, 0]])
而/是按元素行事的
>>> 1/A
array([[ inf, 1. , 0.5 ],
[ 0.33333333, 0.25 , 0.2 ],
[ 0.16666667, 0.14285714, 0.125 ]])
当指数为正时,我没有这样的问题。为什么它对负指数的表现不同?
最佳答案
这主要是类型转换问题。运算符自然会假定您不希望将数字向上转换为不同的类型。 2**-1
与整数最接近的值为0,这可以验证int(2**-1) >>>0
。
首先创建int
类型的数组A
:
A = np.arange(9).reshape(3,3)
>>> A.dtype
dtype('int64')
将数组 A
复制到 A_float
作为 float
类型:
>>> A_float = A.astype(float)
>>> A_float.dtype
dtype('float64')
对两者运行**-1
操作:
>>> A_float**-1
array([[ inf, 1. , 0.5 ],
[ 0.33333333, 0.25 , 0.2 ],
[ 0.16666667, 0.14285714, 0.125 ]])
>>> A**-1
array([[-9223372036854775808, 1, 0],
[ 0, 0, 0],
[ 0, 0, 0]])
观察 numpy 不会自动假定您希望以 float 完成此操作并尝试使用整数来完成此操作。如果您在任一操作数中表示一个 float ,由于“安全”转换规则,您将获得一个 float 输出:
>>> A**-1.0
array([[ inf, 1. , 0.5 ],
[ 0.33333333, 0.25 , 0.2 ],
[ 0.16666667, 0.14285714, 0.125 ]])
另一种选择是强制 np.power
将操作转换为 float :
>>> np.power(A,-1,dtype=float)
array([[ inf, 1. , 0.5 ],
[ 0.33333333, 0.25 , 0.2 ],
[ 0.16666667, 0.14285714, 0.125 ]])
我不确定您为什么使用 1/A
获得 float 结果。 1.0/A
不过效果很好。
关于python - 当指数为负时,为什么 numpy.power 不按元素对数组进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21554885/