我有一个数据集,其中成对的数字由 32 位表示,每个数字表示为两个 8 无符号整数。
我试图获取一个数组中的第一个实部和第二个数组中的复数部分。 然后我尝试对每个部分进行平方,将它们相加并取总和的平方根。 (又名取大小)。 当我尝试使用 numpy.square 对每个数组的元素进行平方时,我不仅得到负值,而且得到不准确的值。 知道发生了什么事/出了什么问题吗?
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
data = np.fromfile(r'C:\Users\Miaou\Desktop\RAW_DATA_000066_000008.bin', dtype="int16")
print(data)
Is = data[0::2]
Qs = data[1::2]
Is_square = np.square(Is, dtype='int16')
Qs_square = np.square(Qs, dtype='int16')
print('Is',Is)
print('Qs',Qs)
print('Is square',Is_square)
print('Qs square',Qs_square)
Output: Is [ 335 -720 8294 ... -3377 3878 6759]
Qs [-2735 4047 1274 ... -279 1319 4918]
Is square [-18847 -5888 -22364 ... 865 31140 5489]
Qs square [ 9121 -5791 -15324 ... 12305 -29711 3940]
最佳答案
您正在经历 integer overflow 。 int16
(有符号)类型的最小值为 -32768
,最大值为 32767
。这样做的原因是因为您只有 16 位(这就是 int16
)的含义。请注意 2^16 = 65536
,但由于它已签名(允许负数),因此我们没有值 0
到 65536
,而是您可以想象它们向下移动,使 0
居中(即 -32768
到 32767
)
让我们以 Is
的第一个元素为例:
>>> 335**2
112225
请注意112225 > 32767
。这意味着你会溢出。它只是不断环绕,直到落在有效范围内:
>>> x = 112225
>>> x = x - 2**16
>>> x
46689 # Still not in the valid range. Repeat.
>>> x = x - 2**16
>>> x
-18847 # Yep, now we are between -32768 and 32768
这里的另一个答案不太正确,因为忽略数据类型是不够的:
>>> Is = np.array([335, -720, 8294, -3377, 3878, 6759]).astype('int16')
>>> Is
array([ 335, -720, 8294, -3377, 3878, 6759], dtype=int16)
>>> Is_sq_nodtype = np.square(Is)
>>> Is_sq_nodtype
array([-18847, -5888, -22364, 865, 31140, 5489], dtype=int16)
numpy
操作保持相同的数据类型。您实际上需要“增加”数据类型以获得更多位。 int32
应该可以满足您的值的要求(您也可以执行 int64
或 float
,具体取决于您的值有多大,这里是一个列表数据类型数量:https://docs.scipy.org/doc/numpy-1.10.0/user/basics.types.html )
工作示例:
>>> Is = np.array([335, -720, 8294, -3377, 3878, 6759]).astype('int16')
array([ 335, -720, 8294, -3377, 3878, 6759], dtype=int16)
>>> Is_sq = np.square(Is, dtype='int32')
>>> Is_sq
array([ 112225, 518400, 68790436, 11404129, 15038884, 45684081], dtype=int32)
HTH。
关于python - Numpy square 返回数组的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61764220/