为什么np.square不能按预期返回输出?

2024-09-28 05:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维numpy矩阵,它的类型是numpy.ndarrayof uint8。 现在,当我对数组执行np.square时,它不会返回预期的结果

下面是创建numpy数组后控制台上的代码及其输出的示例:

arr[0, 0]输出203

现在,, np.square(203)输出41209

但是,, np.square(arr[0, 0])输出249

np.sqrt方法也观察到了这种奇怪的行为。 enter image description here


Tags: 方法代码numpy示例类型np矩阵sqrt
2条回答

np.square与其他ufunc一样,可以返回具有各种数据类型的结果。看起来它“更喜欢”返回匹配的数据类型:

In [109]: np.square(np.array([203], 'uint8'),dtype=int)
Out[109]: array([41209])
In [110]: np.square(np.array([203], 'uint8'),dtype='uint8')
Out[110]: array([249], dtype=uint8)
In [111]: np.square(np.array([203], 'uint8'))
Out[111]: array([249], dtype=uint8)
In [112]: np.square(np.array([203], 'uint8'),dtype='uint8')
Out[112]: array([249], dtype=uint8)
In [113]: np.square(np.array([203], 'uint8'),dtype='uint16')
Out[113]: array([41209], dtype=uint16)
In [114]: np.square(np.array([203], 'uint8'),dtype='int')
Out[114]: array([41209])
In [115]: np.square(np.array([203], 'uint8'),dtype='float')
Out[115]: array([41209.])

https://numpy.org/doc/stable/reference/ufuncs.html#casting-rules

signature参数下

In [118]: np.square.types
Out[118]: 
['b->b',
 'B->B',      # uint8
 'h->h',
 'H->H',
 'i->i',
  ...]

在处理强制转换和数据类型方面有更多的细节,但基本点是,如果使用像unit8这样的“外来”数据类型,请注意溢出等。即使使用“int32”溢出也可能会有问题,但数量要大得多。在对导致浮点的整数进行某些计算时,会出现一个更常见的问题

最近的一个关于带有/=运算符的数据类型的SO

numpy.array's have bizarre behavior with /= operator?

很多时候我不得不问这么多问题-什么是shape,什么是dtype。这些是numpy数组的基本属性。在调试过程中,80%的工作都是正确的

根据numpy.orgnp.uint8Unsigned integer (0 to 255)

import numpy as np

arr = np.array([[203, 32, 45, 34], [34,322,780,54]])
arr1 = arr.astype('uint8')
arr2 = arr.astype('uint16')

sq = np.square(203)
sq8 = np.square(arr1[0,0])
sq16 = np.square(arr2[0,0])

sq, sq8, sq16, type(sq), type(sq8), type(sq16)

输出:

(41209, 249, 41209, numpy.intc, numpy.uint8, numpy.uint16)

41209249中的uint8

num = np.array([41209])
num1 = arr.astype('uint8')
num1
>>> array([249], dtype=uint8)

相关问题 更多 >

    热门问题