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

Are*_*ski 1 python floating-point pack

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

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

In [15]: d.unpack(d.pack(1.23))
Out[15]: (1.2300000190734863,)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

浮点本质上是不精确的,但是你将双精度float(binary64)包装到binary32那里的单精度()空间中.请参阅维基百科有关IEEE浮点格式的文章中的基本和交换格式; Python float格式使用双精度(请参阅标准类型文档 ; 浮点数通常在C中使用double实现).

使用d双精度:

>>> import struct
>>> d = struct.Struct("<d")
>>> d.unpack(d.pack(1.23))
(1.23,)
Run Code Online (Sandbox Code Playgroud)

从格式字符部分:

格式:f,C类型:float,Python类型:float,标准大小:4,脚注:(5)
格式:d,C类型:double,Python类型:float,标准大小:8,脚注:(5)

  1. 对于'f'和'd'转换代码,打包表示使用IEEE 754 binary32(for 'f')或binary64(for 'd')格式,而不管平台使用的浮点格式.