印刷浮动,preserving precision [英] printing float, preserving precision

查看:161
本文介绍了印刷浮动,preserving precision的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写,打印浮点文字另一个程序内使用的程序。

I am writing a program that prints floating point literals to be used inside another program.

多少位,我需要以打印为preserve原浮动的precision?

How many digits do I need to print in order to preserve the precision of the original float?

由于浮体具有 24 *(日志(2)/日志(10))precision的= 7.2247199 十进制数字,我最初的想法是打印8数字应该够了。但是,如果我倒霉,那些 0.2247199 获得分配到左边和的7位数显著的权利,所以我也许应该打印9十进制数。

Since a float has 24 * (log(2) / log(10)) = 7.2247199 decimal digits of precision, my initial thought was that printing 8 digits should be enough. But if I'm unlucky, those 0.2247199 get distributed to the left and to the right of the 7 significant digits, so I should probably print 9 decimal digits.

是我的分析是正确的?有9十进制数字足以让所有的情况?像的printf(%9克,X);

Is my analysis correct? Is 9 decimal digits enough for all cases? Like printf("%.9g", x);?

有一个浮动转换为以最小数为价值所需的十进制数字,在7或8有足够的情况下,一个字符串的标准功能,所以我不打印不必要的数字?

Is there a standard function that converts a float to a string with the minimum number of decimal digits required for that value, in the cases where 7 or 8 are enough, so I don't print unnecessary digits?

请注意:我不能用十六进制浮点常量,因为标准C ++不支持他们。

Note: I cannot use hexadecimal floating point literals, because standard C++ does not support them.

推荐答案

为了保证一个二进制和> 10进制>二进制往返恢复原始二进制值的 IEEE 754 要求

In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires


The original binary value will be preserved by converting to decimal and back again using:[10]

    5 decimal digits for binary16
    9 decimal digits for binary32
    17 decimal digits for binary64
    36 decimal digits for binary128

For other binary formats the required number of decimal digits is

    1 + ceiling(p*log10(2)) 

where p is the number of significant bits in the binary format, e.g. 24 bits for binary32.

在C,您可以使用这些转换的功能的snprintf()和strtof /的strtod / strtold()。

In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold().

当然,在某些情况下甚至更多的数字可能是有用的(无,它们并不总是噪音,这取决于小数转换例程如snprintf的执行())。例如考虑<一href=\"http://www.exploringbinary.com/print-$p$pcision-of-dyadic-fractions-varies-by-language/\">printing向量分数的。

Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions.

这篇关于印刷浮动,preserving precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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