2024-09-28 05:22:55 发布
网友
我有一个二维numpy矩阵,它的类型是numpy.ndarrayof uint8。 现在,当我对数组执行np.square时,它不会返回预期的结果
numpy.ndarray
uint8
np.square
下面是创建numpy数组后控制台上的代码及其输出的示例:
arr[0, 0]输出203
arr[0, 0]
203
现在,, np.square(203)输出41209
np.square(203)
41209
但是,, np.square(arr[0, 0])输出249
np.square(arr[0, 0])
249
np.sqrt方法也观察到了这种奇怪的行为。
np.square与其他ufunc一样,可以返回具有各种数据类型的结果。看起来它“更喜欢”返回匹配的数据类型:
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参数下
signature
In [118]: np.square.types Out[118]: ['b->b', 'B->B', # uint8 'h->h', 'H->H', 'i->i', ...]
在处理强制转换和数据类型方面有更多的细节,但基本点是,如果使用像unit8这样的“外来”数据类型,请注意溢出等。即使使用“int32”溢出也可能会有问题,但数量要大得多。在对导致浮点的整数进行某些计算时,会出现一个更常见的问题
unit8
最近的一个关于带有/=运算符的数据类型的SO
/=
numpy.array's have bizarre behavior with /= operator?
很多时候我不得不问这么多问题-什么是shape,什么是dtype。这些是numpy数组的基本属性。在调试过程中,80%的工作都是正确的
shape
dtype
numpy
根据numpy.orgnp.uint8是Unsigned integer (0 to 255)
np.uint8
Unsigned 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)
41209是249中的uint8:
num = np.array([41209]) num1 = arr.astype('uint8') num1 >>> array([249], dtype=uint8)
np.square
与其他ufunc
一样,可以返回具有各种数据类型的结果。看起来它“更喜欢”返回匹配的数据类型:https://numpy.org/doc/stable/reference/ufuncs.html#casting-rules
在
signature
参数下在处理强制转换和数据类型方面有更多的细节,但基本点是,如果使用像
unit8
这样的“外来”数据类型,请注意溢出等。即使使用“int32”溢出也可能会有问题,但数量要大得多。在对导致浮点的整数进行某些计算时,会出现一个更常见的问题最近的一个关于带有
/=
运算符的数据类型的SOnumpy.array's have bizarre behavior with /= operator?
很多时候我不得不问这么多问题-什么是
shape
,什么是dtype
。这些是numpy
数组的基本属性。在调试过程中,80%的工作都是正确的根据numpy.org
np.uint8
是Unsigned integer (0 to 255)
输出:
41209
是249
中的uint8
:相关问题 更多 >
编程相关推荐