有可应用到一个浮点说明符将自动地格式化输出到的显著数字的必要数量,使得在扫描串回来时,原来的浮点值被获取的printf
宽度说明?
例如,假设我打印float
到2
精确到小数点后:
float foobar = 0.9375;
printf("%.2f", foobar); // prints out 0.94
当我扫描输出0.94
,我没有符合标准的保证,我会得到原始0.9375
浮点值回(在这个例子中,我可能不会)。
我想办法告诉printf
自动浮点值打印到的显著位必要数量,以确保它可以扫描回传给printf
原始值。
我可以使用一些在float.h
的宏来derive the maximum width传递给printf
,但有已经是符自动打印到显著数字的必要数量的 - 或至少最大宽度?
我建议@Jens Gustedt十六进制的解决办法:用一个%。
OP要“打印带有最大精度(或至少是最显著十进制)”。
一个简单的例子是将打印七分之一,如下所示:
#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01
但是,让我们深入挖掘...
在数学上,答案是“0.142857 142857 142857 ......”,更是用有限精度浮点数。假设IEEE 754 double-precision binary。因此,在下面的值OneSeventh = 1.0/7.0
结果。还示出了在前和在后的可表示double
浮点数。
OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after = 0.1428571428571428 769682682968777953647077083587646484375
打印double
的准确的十进制表示具有有限的用途。
C有2个家庭<float.h>
宏来帮助我们。
第一组是显著数字号码在一个字符串打印十进制因此扫描串回来时,我们得到原始浮点。图中示出与C规格的最小值和样品C11编译器。
FLT_DECIMAL_DIG 6, 9 (float) (C11)
DBL_DECIMAL_DIG 10, 17 (double) (C11)
LDBL_DECIMAL_DIG 10, 21 (long double) (C11)
DECIMAL_DIG 10, 21 (widest supported floating type) (C99)
第二组是显著数字串可以被扫描成浮点然后FP印刷,仍保持相同的字符串呈现数目。图中示出与C规格的最小值和样品C11编译器。我相信可以预C99。
FLT_DIG 6, 6 (float)
DBL_DIG 10, 15 (double)
LDBL_DIG 10, 18 (long double)
第一组宏似乎满足显著位OP的目标。但是,宏观并非始终可用。
#ifdef DBL_DECIMAL_DIG
#define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else
#ifdef DECIMAL_DIG
#define OP_DBL_Digs (DECIMAL_DIG)
#else
#define OP_DBL_Digs (DBL_DIG + 3)
#endif
#endif
该“+ 3”是我以前的答案的关键所在。它的中心,如果知道往返转换字符串-FP-字符串(套#2宏可用C89),如何将一个确定FP-串-FP(套#1的宏提供岗位C89)的数字?在一般情况下,加3的结果。
现在还有多少显著数字印刷是已知的,通过<float.h>
驱动。
要打印传单N显著小数位数人们可以使用各种格式。
随着"%e"
,精度领域是数字的领先数字和小数点后的位数。所以- 1
是为了。注:此-1 is not in the initial
int挖= DECIMAL_DIG;`
printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01
随着"%f"
,精度领域是数字的小数点后的位数。对于一些喜欢OneSeventh/1000000.0
,一个需要OP_DBL_Digs + 6
看到所有的显著数字。
printf("%.*f\n", OP_DBL_Digs , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285
注意:许多都使用到"%f"
。显示的小数点后第6位;图6是显示缺省,数量不限的精度。
简短的回答打印浮点数无损(例如,他们可以在以相同数量的回读,除了楠无限远):
printf("%.9g", number)
。printf("%.17g", number)
。不要使用%f
,因为只有指定小数点后多少显著数字,将截断小的数字。作为参考,幻数9和17可以在float.h
限定FLT_DECIMAL_DIG
和DBL_DECIMAL_DIG
找到。
如果你只在位(RESP十六进制模式)感兴趣,你可以使用%a
格式。这样可以保证你:
默认精度足够了值的确切表示如果在基座2存在,并且以其他方式确切表示足够大,以区分类型的双值。
我不得不补充说,这仅仅是因为C99提供。
否,不存在这样的printf宽度说明打印浮点具有最大的精度。让我来解释为什么。
float
和double
的最大精度是可变的,并且取决于float
或double
的实际值。
召回float
和double
存储在sign.exponent.mantissa格式。这意味着有用于为小数目比大数小数部分更多的位。
例如,float
可以很容易地在0.0和0.1之间进行区分。
float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000
但float
没有1e27
和1e27 + 0.1
之间的区别的想法。
r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
这是因为所有的精度(由尾数位的数目的限制)用于开数的大部分,左十进制的。
该%.f
修改只是说你要多少十进制值尽可能格式化去从浮点数打印。 ,所得到的精确度取决于数量的大小,这一事实是你作为程序员来处理。 printf
不能/不处理你。
简单地使用从<float.h>
和可变宽度转换符(".*"
)宏:
float f = 3.14159265358979323846;
printf("%.*f\n", FLT_DIG, f);
我运行一个小实验,以验证与DBL_DECIMAL_DIG
是印刷确实恰好保存数字的二进制表示。原来,因为我试过的编译器和C库,DBL_DECIMAL_DIG
确实是需要的数字甚至一个数字的号码,打印少创建一个显著的问题。
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union {
short s[4];
double d;
} u;
void
test(int digits)
{
int i, j;
char buff[40];
double d2;
int n, num_equal, bin_equal;
srand(17);
n = num_equal = bin_equal = 0;
for (i = 0; i < 1000000; i++) {
for (j = 0; j < 4; j++)
u.s[j] = rand();
if (isnan(u.d))
continue;
n++;
sprintf(buff, "%.*g", digits, u.d);
sscanf(buff, "%lg", &d2);
if (u.d == d2)
num_equal++;
if (memcmp(&u.d, &d2, sizeof(double)) == 0)
bin_equal++;
}
printf("Tested %d values with %d digits: %d found numericaly equal, %d found binary equal\n", n, digits, num_equal, bin_equal);
}
int
main()
{
test(DBL_DECIMAL_DIG);
test(DBL_DECIMAL_DIG - 1);
return 0;
}
我与微软的C编译器19.00.24215.1和gcc版本6.3.0 20170516(Debian的6.3.0-18 + deb9u1)运行此。使用少了一个十进制数半部比较准确人数相等的数量。 (我也验证为确实是用来生产约一百万个不同的数字,rand()
。)下面是详细的结果。
Tested 999523 values with 17 digits: 999523 found numericaly equal, 999523 found binary equal Tested 999523 values with 16 digits: 549780 found numericaly equal, 549780 found binary equal
Tested 999492 values with 17 digits: 999492 found numericaly equal, 999492 found binary equal Tested 999492 values with 16 digits: 546615 found numericaly equal, 546615 found binary equal
在我的意见,回答一个我感叹,我早就想一些方法来打印所有显著位数小数形式的浮点值,在大部分的问题问了同样的方式。嗯,我终于坐下来写的。这不是很完美的,这是演示代码,打印更多的信息,但它主要适用于我的测试。请让我知道,如果你(即任何人)想驱动该测试整个包装程序的副本。
static unsigned int
ilog10(uintmax_t v);
/*
* Note: As presented this demo code prints a whole line including information
* about how the form was arrived with, as well as in certain cases a couple of
* interesting details about the number, such as the number of decimal places,
* and possibley the magnitude of the value and the number of significant
* digits.
*/
void
print_decimal(double d)
{
size_t sigdig;
int dplaces;
double flintmax;
/*
* If we really want to see a plain decimal presentation with all of
* the possible significant digits of precision for a floating point
* number, then we must calculate the correct number of decimal places
* to show with "%.*f" as follows.
*
* This is in lieu of always using either full on scientific notation
* with "%e" (where the presentation is always in decimal format so we
* can directly print the maximum number of significant digits
* supported by the representation, taking into acount the one digit
* represented by by the leading digit)
*
* printf("%1.*e", DBL_DECIMAL_DIG - 1, d)
*
* or using the built-in human-friendly formatting with "%g" (where a
* '*' parameter is used as the number of significant digits to print
* and so we can just print exactly the maximum number supported by the
* representation)
*
* printf("%.*g", DBL_DECIMAL_DIG, d)
*
*
* N.B.: If we want the printed result to again survive a round-trip
* conversion to binary and back, and to be rounded to a human-friendly
* number, then we can only print DBL_DIG significant digits (instead
* of the larger DBL_DECIMAL_DIG digits).
*
* Note: "flintmax" here refers to the largest consecutive integer
* that can be safely stored in a floating point variable without
* losing precision.
*/
#ifdef PRINT_ROUND_TRIP_SAFE
# ifdef DBL_DIG
sigdig = DBL_DIG;
# else
sigdig = ilog10(uipow(FLT_RADIX, DBL_MANT_DIG - 1));
# endif
#else
# ifdef DBL_DECIMAL_DIG
sigdig = DBL_DECIMAL_DIG;
# else
sigdig = (size_t) lrint(ceil(DBL_MANT_DIG * log10((double) FLT_RADIX))) + 1;
# endif
#endif
flintmax = pow((double) FLT_RADIX, (double) DBL_MANT_DIG); /* xxx use uipow() */
if (d == 0.0) {
printf("z = %.*s\n", (int) sigdig + 1, "0.000000000000000000000"); /* 21 */
} else if (fabs(d) >= 0.1 &&
fabs(d) <= flintmax) {
dplaces = (int) (sigdig - (size_t) lrint(ceil(log10(ceil(fabs(d))))));
if (dplaces < 0) {
/* XXX this is likely never less than -1 */
/*
* XXX the last digit is not significant!!! XXX
*
* This should also be printed with sprintf() and edited...
*/
printf("R = %.0f [%d too many significant digits!!!, zero decimal places]\n", d, abs(dplaces));
} else if (dplaces == 0) {
/*
* The decimal fraction here is not significant and
* should always be zero (XXX I've never seen this)
*/
printf("R = %.0f [zero decimal places]\n", d);
} else {
if (fabs(d) == 1.0) {
/*
* This is a special case where the calculation
* is off by one because log10(1.0) is 0, but
* we still have the leading '1' whole digit to
* count as a significant digit.
*/
#if 0
printf("ceil(1.0) = %f, log10(ceil(1.0)) = %f, ceil(log10(ceil(1.0))) = %f\n",
ceil(fabs(d)), log10(ceil(fabs(d))), ceil(log10(ceil(fabs(d)))));
#endif
dplaces--;
}
/* this is really the "useful" range of %f */
printf("r = %.*f [%d decimal places]\n", dplaces, d, dplaces);
}
} else {
if (fabs(d) < 1.0) {
int lz;
lz = abs((int) lrint(floor(log10(fabs(d)))));
/* i.e. add # of leading zeros to the precision */
dplaces = (int) sigdig - 1 + lz;
printf("f = %.*f [%d decimal places]\n", dplaces, d, dplaces);
} else { /* d > flintmax */
size_t n;
size_t i;
char *df;
/*
* hmmmm... the easy way to suppress the "invalid",
* i.e. non-significant digits is to do a string
* replacement of all dgits after the first
* DBL_DECIMAL_DIG to convert them to zeros, and to
* round the least significant digit.
*/
df = malloc((size_t) 1);
n = (size_t) snprintf(df, (size_t) 1, "%.1f", d);
n++; /* for the NUL */
df = realloc(df, n);
(void) snprintf(df, n, "%.1f", d);
if ((n - 2) > sigdig) {
/*
* XXX rounding the integer part here is "hard"
* -- we would have to convert the digits up to
* this point back into a binary format and
* round that value appropriately in order to
* do it correctly.
*/
if (df[sigdig] >= '5' && df[sigdig] <= '9') {
if (df[sigdig - 1] == '9') {
/*
* xxx fixing this is left as
* an exercise to the reader!
*/
printf("F = *** failed to round integer part at the least significant digit!!! ***\n");
free(df);
return;
} else {
df[sigdig - 1]++;
}
}
for (i = sigdig; df[i] != '.'; i++) {
df[i] = '0';
}
} else {
i = n - 1; /* less the NUL */
if (isnan(d) || isinf(d)) {
sigdig = 0; /* "nan" or "inf" */
}
}
printf("F = %.*s. [0 decimal places, %lu digits, %lu digits significant]\n",
(int) i, df, (unsigned long int) i, (unsigned long int) sigdig);
free(df);
}
}
return;
}
static unsigned int
msb(uintmax_t v)
{
unsigned int mb = 0;
while (v >>= 1) { /* unroll for more speed... (see ilog2()) */
mb++;
}
return mb;
}
static unsigned int
ilog10(uintmax_t v)
{
unsigned int r;
static unsigned long long int const PowersOf10[] =
{ 1LLU, 10LLU, 100LLU, 1000LLU, 10000LLU, 100000LLU, 1000000LLU,
10000000LLU, 100000000LLU, 1000000000LLU, 10000000000LLU,
100000000000LLU, 1000000000000LLU, 10000000000000LLU,
100000000000000LLU, 1000000000000000LLU, 10000000000000000LLU,
100000000000000000LLU, 1000000000000000000LLU,
10000000000000000000LLU };
if (!v) {
return ~0U;
}
/*
* By the relationship "log10(v) = log2(v) / log2(10)", we need to
* multiply "log2(v)" by "1 / log2(10)", which is approximately
* 1233/4096, or (1233, followed by a right shift of 12).
*
* Finally, since the result is only an approximation that may be off
* by one, the exact value is found by subtracting "v < PowersOf10[r]"
* from the result.
*/
r = ((msb(v) * 1233) >> 12) + 1;
return r - (v < PowersOf10[r]);
}