struct.unpack(struct.pack(float))是否具有舍入错误? [英] struct.unpack(struct.pack(float)) has roundoff error?

查看:142
本文介绍了struct.unpack(struct.pack(float))是否具有舍入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,C类型:float,Python类型:float,标准尺寸:4,脚注:(5)
格式:d,C类型:double,Python类型:float,标准大小:8,脚注:(5)

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. 对于'f''d'转换代码,打包表示使用IEEE 754二进制32(对于'f')或二进制64(对于'd')格式,而与平台使用的浮点格式无关.
  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.

这篇关于struct.unpack(struct.pack(float))是否具有舍入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆