浮点数到字符串并返回的无损转换:可能吗? [英] lossless conversion of float to string and back: is it possible?

查看:60
本文介绍了浮点数到字符串并返回的无损转换:可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题涉及C/x86上使用的IEEE标准浮点数.

This question refers to the IEEE standard floating point numbers used on C/x86.

是否可以将任何数字(即不包括NaN之类的特殊值)表示为浮点数或双精度数作为十进制字符串,以便将该字符串转换回浮点数/双精度数始终会产生原始数字?

Is it possible to represent any numeric (i.e. excluding special values such as NaN) float or double as a decimal string such that converting that string back to a float/double will always yield exactly the original number?

如果没有,什么算法可以告诉我给定的数字是否会发生转换错误?

If not, what algorithm tells me whether a given number will suffer a conversion error?

如果是这样,请考虑以下问题:当转换为二进制时,某些十进制小数在数值上将与原始十进制值不同,但是反之则不成立(因为二进制具有一定的精度,因此任何十进制扩展都是有限的,并且如果没有被截断,则是完美的),所以这是另一个问题...

If so, consider this: some decimal fractions, when converted to binary, will not be numerically the same as the original decimal value, but the reverse is not true (because the binary has bounded precision so any decimal expansion is finite and perfect if not truncated), so here's another question...

是否有必要将故意的错误引入小数表示形式,以欺骗atof(或其他)函数以产生确切的原始数字,或者天真,不截断的toString函数是否足够(假设一般情况下可以进行精确转换)?

Is it ever necessary to introduce deliberate errors into the decimal representation in order to trick the atof (or other) function into yielding the exact original number, or will a naive, non-truncating toString function be adequate (assuming exact conversion is possible in general)?

推荐答案

根据此页面:

实际上,IEEE754-1985标准说17位十进制数字是 在所有情况下都足够.但是,似乎标准有点 不确定是否符合标准的实现必须保证无损 使用17位数字时进行转换.

Actually, the IEEE754-1985 standard says that 17 decimal digits is enough in all cases. However, it seems that the standard is a little vague on whether conforming implementations must guarantee lossless conversion when 17 digits are used.

因此,将double作为至少包含17位数字(正确舍入)的十进制字符串存储,将确保可以将其转换回二进制double而不会丢失任何数据.

So storing a double as a decimal string with at least 17 digits (correctly rounded) will guarantee that it can be converted back to binary double without any data loss.

换句话说,如果将每个可能的双精度值都转换为17位十进制字符串(正确舍入),则它们都将映射到不同的值.这样就不会丢失数据.

In other words, if every single possible double-precision value were to be converted to a decimal string of 17 digits (correctly rounded), they will all map to different values. Thus there is no data-loss.

我不确定单精度的最小截止值.但是我怀疑这将是8位或9位数字.

I'm not sure on the minimum cut-off for single-precision though. But I'd suspect that it will be 8 or 9 digits.

这篇关于浮点数到字符串并返回的无损转换:可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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