简体   繁体   中英

Why does the Python ** operator behave differently on arrays and scalars

I don't understand the justification for the following behavior of the ** operator in Python. This returns a float:

>>> 10**-1
0.1

And this returns integers:

>>> y=np.array([10,10,10])
>>> y
array([10, 10, 10])
>>> y**-1
array([0, 0, 0])

Why?!

The following works, but the above seems very wrong.

>>> y**-1.0
array([ 0.1,  0.1,  0.1])

For efficiency, numpy arrays are restricted to a specified type, for example with yours:

>>> y=np.array([10,10,10])
>>> y.dtype
dtype('int64')

Because an int can't represent the fractional part, it's discarded. If you use a floating point array like this, the result is what you expected:

>>> y=np.array([10,10,10], dtype='float32')
>>> y.dtype
dtype('float32')
>>> y**-1
array([ 0.1,  0.1,  0.1], dtype=float32)

Also, if the list you pass in initially contains float types, the dtype will default to float64 :

>>> y=np.array([10.0 ,10.0 ,10.0])
>>> y.dtype
dtype('float64')
>>> y**-1
array([ 0.1,  0.1,  0.1])

numpy实现它的任何包含两个int结果的数学运算..至少那在很大程度上是我的经验

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM