IEEE“双精度”的精确文本表示
我需要以人类可读的文本形式表示 IEEE 754-1985 双(64 位)浮点数,条件是文本形式可以解析回完全相同相同的(位-明智的)数字。
如果不打印原始字节,这是否可能/实用? 如果是,那么执行此操作的代码将不胜感激。
I need to represent an IEEE 754-1985 double (64-bit) floating point number in a human-readable textual form, with the condition that the textual form can be parsed back into exactly the same (bit-wise) number.
Is this possible/practical to do without just printing the raw bytes?
If yes, code to do this would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最佳选择:使用 C99 十六进制浮点格式:
以这种方式生成的字符串可以使用 C99
strtod( )
函数以及转换回
double
scanf() 函数。其他几种语言也支持这种格式。一些示例:十六进制格式的优点是所有表示形式都是精确。因此,即使有人更改了执行转换的舍入模式,将字符串转换回浮点数也始终会给出原始数字。对于不精确的格式来说,情况并非如此。
如果您出于某种原因不想使用十六进制格式,并且愿意假设舍入模式将始终舍入到最接近的值(默认),那么您可以将数据格式化为至少为 17 的小数有效数字。如果您有一个正确的舍入转换例程(大多数(不是所有)平台都有),这将保证您可以进行从双精度到字符串的往返转换,而不会损失任何准确性。
Best option: Use the C99 hexadecimal floating point format:
Strings produced this way can be converted back into
double
with the C99strtod( )
function, and also with thescanf( )
functions. Several other languages also support this format. Some examples:The hexadecimal format has the advantage that all representations are exact. Thus, converting the string back into floating-point will always give the original number, even if someone changes the rounding mode in which the conversion is performed. This is not true for inexact formats.
If you don't want to use the hexadecimal format for whatever reason, and are willing to assume that the rounding mode will always be round to nearest (the default), then you can get away with formatting your data as decimals with at least 17 significant digits. If you have a correctly rounded conversion routine (most -- not all -- platforms do), this will guarantee that you can do a round trip from double to string and back without any loss of accuracy.
听起来像你想要的 Burger 算法(PDF):
示例源代码(在 C 和Scheme 中)也可用。
这是 Python 3.x 中使用的算法,用于确保浮点型可以在字符串和字符串之间相互转换,而不会损失任何准确性。在 Python 2.x 中,
float
始终用 17 位有效数字表示,因为:Sound like you want Burger's algorithm (PDF):
Sample source code (in C and Scheme) is available as well.
This is the algorithm used in Python 3.x to ensure
float
s can be converted to strings and back without any loss of accuracy. In Python 2.x,float
s were always represented with 17 significant digits because:.NET 框架对此有一个往返格式:
来自文档:
当然可以用大多数任何语言重新创建该方法。
The .NET framework has a round-trip format for this:
From the documentation:
This method could of course be recreated in most any language.
是的,这是可以做到的,尽管实现取决于语言。基本思想就是以足够的精度打印出来。
请注意,反之则不然:一些可以用十进制精确表示的数字根本无法用二进制表示。
Yes, it can be done, though the implementation depends on the language. The basic idea is simply to print it out with sufficient precision.
Note that the reverse is not true though: some numbers that can be represented precisely in decimal simply cannot be represented in binary.