表示任何双精度值所需的最大字符长度是多少?

2022-01-09 00:00:00 floating-point c c++

当我将无符号的 8 位 int 转换为字符串时,我知道结果将始终最多为 3 个字符(对于 255),对于有符号的 8 位 int,我们需要 4 个字符,例如-128".

When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128".

现在我真正想知道的是浮点值也是一样的.将任何double"或float"值表示为字符串所需的最大字符数是多少?

Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" or "float" value as a string?

假设常规 C/C++ 双精度 (IEEE 754) 和常规十进制扩展(即没有 %e printf 格式).

Assume a regular C/C++ double (IEEE 754) and normal decimal expansion (i.e. no %e printf-formatting).

我什至不确定真正小的数字(即 0.234234)是否会比真正的大数字(表示整数的双精度数)更长?

I'm not even sure if the really small number (i.e. 0.234234) will be longer than the really huge numbers (doubles representing integers)?

推荐答案

标准头文件 在 C 中,或 在 C++, 包含几个与浮点类型的范围和其他指标有关的常量.其中之一是 DBL_MAX_10_EXP,表示所有 double 值所需的最大 10 次幂指数.由于 1eN 需要 N+1 个数字来表示,而且可能还有负号,那么答案是

The standard header <float.h> in C, or <cfloat> in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is DBL_MAX_10_EXP, the largest power-of-10 exponent needed to represent all double values. Since 1eN needs N+1 digits to represent, and there might be a negative sign as well, then the answer is

int max_digits = DBL_MAX_10_EXP + 2;

这假设指数大于表示最大可能尾数值所需的位数;否则,也会有一个小数点后跟更多的数字.

This assumes that the exponent is larger than the number of digits needed to represent the largest possible mantissa value; otherwise, there will also be a decimal point followed by more digits.

更正

最长的数实际上是最小的可表示的负数:它需要足够的位数来覆盖指数和尾数.该值为 -pow(2, DBL_MIN_EXP - DBL_MANT_DIG),其中 DBL_MIN_EXP 为负数.很容易看出(并通过归纳证明)-pow(2,-N) 需要 3+N 个字符来表示非科学十进制表示(-0.",后跟 N 个数字).所以答案是

The longest number is actually the smallest representable negative number: it needs enough digits to cover both the exponent and the mantissa. This value is -pow(2, DBL_MIN_EXP - DBL_MANT_DIG), where DBL_MIN_EXP is negative. It's fairly easy to see (and prove by induction) that -pow(2,-N) needs 3+N characters for a non-scientific decimal representation ("-0.", followed by N digits). So the answer is

int max_digits = 3 + DBL_MANT_DIG - DBL_MIN_EXP

对于 64 位 IEEE double,我们有

For a 64-bit IEEE double, we have

DBL_MANT_DIG = 53
DBL_MIN_EXP = -1023
max_digits = 3 + 53 - (-1023) = 1079

相关文章