struct.unpack(struct.pack(float)) 有舍入误差?

struct.unpack(struct.pack(float)) has roundoff error?

在测试我的库 Construct 时,我发现在构建数字然后解析回浮点数时测试失败。浮点数不应该完全表示为内存中的浮点数吗?

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

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

浮点本质上是不精确的,但您将双精度浮点数 (binary64) 打包成单精度浮点数 (binary32) space。参见Basic and interchange formats in the Wikipedia article on IEEE floating point formats; the Python float format uses double precision (see the 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.