问题描述
在测试我的库构造时,我发现在构建数字然后解析回数字时测试失败浮动.浮点数应该不完全代表内存中的浮点数吗?
When testing my library, Construct, I found out that tests fail when numbers are built then parsed back to a float. Should floats not be represented exactly as in-memory floats?
In [14]: d = struct.Struct("<f")
In [15]: d.unpack(d.pack(1.23))
Out[15]: (1.2300000190734863,)
推荐答案
浮点本质上是不精确的,但是您要将一个双精度浮点(binary64
)打包到一个单精度(binary32
)空间中.请参阅Wikipedia中有关IEEE浮动的文章中的 基本和互换格式 点格式; Python float
格式使用双精度(请参见标准类型docs ; 浮点数通常使用C中的double来实现.
Floating point is inherently imprecise, but you are packing a double-precision float (binary64
) into a single-precision (binary32
) space there. See 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; Floating point numbers are usually implemented using double in C).
使用d
使用双精度:
>>> import struct
>>> d = struct.Struct("<d")
>>> d.unpack(d.pack(1.23))
(1.23,)
在 格式化字符部分:
- 对于
'f'
和'd'
转换代码,打包表示使用IEEE 754二进制32(对于'f'
)或二进制64(对于'd'
)格式,而与平台使用的浮点格式无关.
- 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.
这篇关于struct.unpack(struct.pack(float))是否具有舍入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!