gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:17 25 4
gpt4 key购买 nike

测试我的图书馆时,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.

关于python - struct.unpack(struct.pack(float)) 有舍入误差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39619636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com