Skip to main content
 首页 » 编程设计

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

2025年05月04日17jackei

测试我的图书馆时,Construct ,我发现当构建数字然后解析回 float 时测试失败。不应该将 float 完全表示为内存中的 float 吗?

In [14]: d = struct.Struct("<f") 
 
In [15]: d.unpack(d.pack(1.23)) 
Out[15]: (1.2300000190734863,) 

请您参考如下方法:

浮点本质上是不精确的,但您将 double float (binary64) 打包到单精度 (binary32) 空间中。参见 Basic and interchange formats在关于 IEEE 浮点格式的维基百科文章中; Python float 格式使用 double (参见 standard types docs ; float 通常在 C 中使用 double )。

使用d来使用 double :

>>> 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.