pythonnumpy-Square值问题

pythonnumpy-Square值问题,python,numpy,Python,Numpy,我试图将numpy数组中的所有元素平方,但结果并不是我所期望的(即一些是负数,没有一个是实际的平方值)。谁能解释一下我做错了什么和/或发生了什么事 import numpy as np import math f = 'file.bin' frameNum = 25600 channelNum = 2640 data = np.fromfile(f,dtype=np.int16) total = frameNum*channelNum*2 rs = data[:total].reshape(c

我试图将numpy数组中的所有元素平方,但结果并不是我所期望的(即一些是负数,没有一个是实际的平方值)。谁能解释一下我做错了什么和/或发生了什么事

import numpy as np
import math
f = 'file.bin'
frameNum = 25600
channelNum = 2640

data = np.fromfile(f,dtype=np.int16)
total = frameNum*channelNum*2
rs = data[:total].reshape(channelNum,-1) #reshaping the data a little. Omitting added values at the end.  


I = rs[:,::2] # pull out every other column

print "Shape :", I.shape
print "I : ", I[1,:10]
print "I**2 : ", I[1,:10]**2
print "I*I : ",I[1,:10]* I[1,:10]
print "np.square : ",np.square(I[1,:10])
exit()
输出:

Shape : (2640L, 25600L)
I :  [-5302 -5500 -5873 -5398 -5536 -6708 -6860 -6506 -6065 -6363]
I**2 :  [ -3740 -27632  20193 -25116 -23552 -25968   4752  -8220  18529 -13479]
I*I :  [ -3740 -27632  20193 -25116 -23552 -25968   4752  -8220  18529 -13479]
np.square :  [ -3740 -27632  20193 -25116 -23552 -25968   4752  -8220  18529 -13479]

有什么建议吗

这是因为
dtype=np.int16
。您只允许16位表示数字,
-5302**2
大于有符号16位整数可以采用的最大值(32767)。因此,您只看到结果的最低16位,其中第一位被解释(或者,从您的角度来看,被误解)为符号位

将数组转换为不同的数据类型-例如

I = np.array( I, dtype=np.int32 )

在执行可能超出范围的数值操作之前

对于
dtype=np.int16
,可以平方的最大值整数是+181和-181。182的平方比32767大,因此溢出。即使使用
dtype=np.int32
表示法,您可以平方的最高量级整数是+46340和-46340:46341的平方溢出。

这就是原因:

>>> a = np.array([-5302, -5500], dtype=np.int16)
>>> a * a
array([ -3740, -27632], dtype=int16)
这就是解决方案:

b = np.array([-5302, -5500], dtype=np.int32)
>>> b * b
>>> array([28111204, 30250000], dtype=int32)
更改:

data = np.fromfile(f, dtype=np.int16)
进入:


这肯定只是整数溢出吗?16位不足以容纳该大小的数字的平方尝试在读取值后将值转换为32位。这使数组的大小增加了一倍,但是如果你想在不溢出的情况下对值进行平方运算,你需要更多的位。我不认为这是问题所在,因为如果我手工构建一个小版本的数组,它似乎可以工作:在[1]中:在[2]中导入numpy作为np:I=np.array([-5302,-5500,-5873,-5398])在[3]中:在[4]中导入数学:i*i Out[4]:数组([2811120430250000,3449212929138404])在这种情况下,
i
不是16位。查看
i.dtype
。使用`i=np.array([-5302,-5500,-5873,-5398],dtype=np.int16)试试看`
data = np.fromfile(f, dtype=np.int16)
data = np.fromfile(f, dtype=np.in16).astype(np.int32)