问题描述
使用负数组时,numpy.power或**和/处理数组时有什么区别?以及为什么numpy.power不能按文档.
What is the difference between numpy.power or ** for negative exponents and / when working with arrays? and why does numpy.power not act element-wise as described in the documentation.
例如,使用python 2.7.3:
For example, using 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似乎不是按元素进行操作
It appears that ** and numpy.power are not acting element-wise when the exponent is negative
>>> 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 ]])
当指数为正时,我没有此类问题.为什么负指数的行为会有所不同?
I have no such problems when the exponent is positive. Why does it behave differently for negative exponents?
推荐答案
这主要是转换问题.运营商自然会以为您不希望将号码上载到其他类型. 2**-1
与整数的最接近值是0,可以验证int(2**-1) >>>0
.
This is primarily an issue of casting. Operators naturally assume that you do not wish to upcast a number to a different type. The closest value of 2**-1
with integers is 0, this can be verified int(2**-1) >>>0
.
首先创建类型为int
的数组A
:
First create array A
of type int
:
A = np.arange(9).reshape(3,3)
>>> A.dtype
dtype('int64')
将数组A
复制到A_float
作为类型float
:
Copy array A
to A_float
as type 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形式完成此操作,而是尝试使用整数来完成此操作.如果您在两个操作数中都表示浮点数,则由于安全"转换规则,您将获得浮点数输出:
Observe numpy does not automatically assume you want to complete this operation as float and attempts to accomplish this with integers. If you signify a float in either operand you will obtain a float output due to the "safe" casting rules:
>>> A**-1.0
array([[ inf, 1. , 0.5 ],
[ 0.33333333, 0.25 , 0.2 ],
[ 0.16666667, 0.14285714, 0.125 ]])
另一种选择是强制np.power
将操作强制转换为浮点型:
Another option is to force np.power
to cast the operation as a 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
获得浮点结果. 1.0/A
正常工作.
I am not sure why you are obtaining a float result with 1/A
. 1.0/A
works just fine however.
这篇关于当指数为负数时,为什么numpy.power不对数组进行元素处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!