简体   繁体   中英

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

Let's suppose that we have always the same C locale.

Is it possible to find such float value that in code bellow 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. But I can not find such number (value?= restored_x) is it exists?

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.

For x = 0.0001220703052240423858165740966796875f , restored_x does not equal x . Even if the %.6g is changed to .8g , restored_x will not equal x ; it will be 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.)

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.

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. It is not sufficient to distinguish float values which are close but not equal; there exist unequal float values that will print identically with %.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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