我试图通过向下转换浮点数据类型来减少内存消耗。

我检查了 np.float16 的范围:

np.finfo(np.float16)
finfo(resolution=0.001, min=-6.55040e+04, max=6.55040e+04, dtype=float16)

这显示了 -6.55040e+04 < 2053 < 6.55040e+04
现在:

s = pd.Series([2051,2052,2053,2054])
s.astype(np.float16)

0    2052.0
1    2052.0
2    2052.0
3    2054.0

为什么会这样?

更新
np.finfo 借用文档
numpy.finfo
class numpy.finfo[source]
Machine limits for floating point types.

Parameters:
dtype : float, dtype, or instance

Kind of floating point data-type about which to get information.

Attributes

eps (float) The smallest representable positive number such that 1.0 + eps != 1.0. Type of eps is an appropriate floating point type.
epsneg  (floating point number of the appropriate type) The smallest representable positive number such that 1.0 - epsneg != 1.0.
iexp    (int) The number of bits in the exponent portion of the floating point representation.
machar  (MachAr) The object which calculated these parameters and holds more detailed information.
machep  (int) The exponent that yields eps.
max (floating point number of the appropriate type) The largest representable number.
maxexp  (int) The smallest positive power of the base (2) that causes overflow.
min (floating point number of the appropriate type) The smallest representable number, typically -max.
minexp  (int) The most negative power of the base (2) consistent with there being no leading 0’s in the mantissa.
negep   (int) The exponent that yields epsneg.
nexp    (int) The number of bits in the exponent including its sign and bias.
nmant   (int) The number of bits in the mantissa.
precision   (int) The approximate number of decimal digits to which this kind of float is precise.
resolution  (floating point number of the appropriate type) The approximate decimal resolution of this type, i.e., 10**-precision.
tiny    (float) The smallest positive usable number. Type of tiny is an appropriate floating point type.

最佳答案

这不是关于 minmax ,它们分别确定 float16 可以采用的最低和最高值,而是 resolution ,或者两个值之间的最小差异,然后才被认为是相同的。
finfo 显示 float16 的分辨率为 0.001 ,即 4 位有效数字。您的案例中的数字 2 是第 4 个有效数字。

关于python - 被 pandas dtype 转换为 np.float16 值 2053 变成 2052 的困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55881160/

10-11 20:30