简体   繁体   English

是否有可能找到不适合 %.6g 的浮点数

[英]is it possible to find float that not fit to %.6g

Let's suppose that we have always the same C locale.假设我们始终使用相同的 C 语言环境。

Is it possible to find such float value that in code bellow restored_x != value是否有可能在下面的代码中找到这样的浮点value restore_x restored_x != value

float x = value;
char s[32];
sprintf(s, "%.6g", x);//do not use snprintf for simplicity
float restored_x = 0.;
sscanf(s, "%g", &restored_x);

In other words I find out code that uses %.6g for serialisation, and as I know decimal representation of binary float is not exactly 6 digits after "dot", it may be 7 or more.换句话说,我发现使用%.6g进行序列化的代码,并且我知道二进制浮点数的十进制表示在“点”之后不完全是 6 位,它可能是 7 位或更多位。 But I can not find such number (value?= restored_x) is it exists?但是我找不到这样的数字(值?=restored_x)它存在吗?

I don't take into consideration NaN and +-Inf and so on special case, because of there is asserts that verify input in function that uses %.6g for serialisation.我不考虑 NaN 和 +-Inf 等特殊情况,因为有断言可以验证 function 中的输入,它使用%.6g进行序列化。

For x = 0.0001220703052240423858165740966796875f , restored_x does not equal x .对于x = 0.0001220703052240423858165740966796875frestored_x不等于x Even if the %.6g is changed to .8g , restored_x will not equal x ;即使%.6g更改为.8grestored_x也不会等于x it will be 0.0001220703125.它将是 0.0001220703125。

(This assumes the C implementation uses IEEE-754 binary32 for float and correct rounding with round-to-nearest ties-to-even, none of which is required by the C standard.) (这假设 C 实现使用 IEEE-754 binary32 进行float和正确舍入,并使用四舍五入到最近的关系,C 标准都不需要。)

64,452,836 of the floating-point values (about 1.5% of the finite values) require nine digits to survive a round-trip binary-decimal-binary conversion. 64,452,836 个浮点值(大约是有限值的 1.5%)需要 9 位数字才能在往返二进制 - 十进制 - 二进制转换中存活。

6 ( FLT_DIG ) is the max number of decimal digits that can be round-tripped from decimal, to float , and back to decimal without loss. 6 ( FLT_DIG ) 是十进制数字的最大数量,可以从十进制到float ,然后返回到十进制而不会丢失。 It is not sufficient to distinguish float values which are close but not equal;仅区分接近但不相等的float值是不够的; there exist unequal float values that will print identically with %.6g .存在不相等的float值,它们将与%.6g打印相同。 You need FLT_DECIMAL_DIG (9) digits to safely round-trip a float through a decimal string in the worst case, and far more to represent the value exactly in decimal.在最坏的情况下,您需要FLT_DECIMAL_DIG (9) 位来安全地通过十进制字符串往返float ,并且需要更多以精确地以十进制表示值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM