的struct.unpack(struct.pack(float))有舍入错误吗?

在测试我的库Construct时,我发现在构建数字然后将其解析回浮点数时测试失败.浮点数是否应该不完全代表内存中的浮点数?

In [14]: d = struct.Struct("<f")

In [15]: d.unpack(d.pack(1.23))
Out[15]: (1.2300000190734863,)

解决方法:

浮点在本质上是不精确的,但是您要将双精度浮点数(binary64)打包到那里的单精度(binary32)空间中.参见Wikipedia文章中有关IEEE浮点格式的Basic and interchange formats; Python浮点格式使用双精度(请参见standard types docs;浮点数通常使用C中的double实现).

使用d来使用双精度:

>>> import struct
>>> d = struct.Struct("<d")
>>> d.unpack(d.pack(1.23))
(1.23,)

Format characters section

format: f, C Type: float, Python type: float, Standard size: 4, Footnote: (5)
format: d, C Type: double, Python type: float, Standard size: 8, Footnote: (5)

  1. For the 'f' and 'd' conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f') or binary64 (for 'd') format, regardless of the floating-point format used by the platform.
上一篇:Perl的pack函数在Java中等效


下一篇:Python GUI文本编辑器