什么是重新present任何双重价值需要的字符的最大长度? [英] What is the maximum length in chars needed to represent any double value?
问题描述
当我转换成一个无符号的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".
现在什么,我其实不知道是浮点值同样的事情。什么是重新present所需字符的最大数量的双或浮动值作为一个字符串?
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)会比真正庞大的数字(双打重新presenting整数)?再
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)?
推荐答案
标准头< FLOAT.H>
在C或&LT ; cfloat>
在C ++中,包含了几个常数做的范围和浮点类型的其他指标。其中之一是 DBL_MAX_10_EXP
,最大功率的-10指数重新present所有双击
值需要。由于 1EN
需要 N + 1
数字重新present,并有可能是一个负号为好,那么答案
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;
此假定指数比的重新present最大可能尾数值所需的位数大;否则,也将有一个小数点后跟多个数字。
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.
修正
最长的数量实际上是最小的重presentable负数:需要足够的数字来涵盖指数和尾数。此值 -pow(2 DBL_MIN_EXP - DBL_MANT_DIG)
,其中 DBL_MIN_EXP
为负。这是很容易看到(和通过感应证明)的 -pow(2 -N)
需求 3 + N
对于非科学小数重presentation字符( - 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双,我们有
For a 64-bit IEEE double, we have
DBL_MANT_DIG = 53
DBL_MIN_EXP = -1023
max_digits = 3 + 53 - (-1023) = 1079
这篇关于什么是重新present任何双重价值需要的字符的最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!