[英]Precision of floats with printf
眾所周知,當您使用printf
輸出float
值時,精度有限。
但是,有一個技巧可以提高輸出的准確性,如下例所示:
#include <stdio.h>
int main()
{
float f = 1318926965; /* 10 random digits */
printf("%10.f\n", f); /* prints only 8 correct digits */
printf("%10d\n", *(int*)&f); /* prints all digits correctly */
return 0;
}
我的問題是,為什么人們不經常使用這個技巧?
愚人節?
您的“隨機數” 1318926965
具有十進制和浮點形式的相同基礎表示。
嘗試其他值,例如10
。 它將打印為:
10
1092616192
所以回答你的問題:
and my question is, why don't people use this trick more often?
因為一年中只有一天是愚人節...剩下的時間訣竅不起作用......
嘗試使用不同數字的相同技巧,例如2318926965。
#include <stdio.h>
int main()
{
float f = 2318926965; /* 10 random digits */
printf("%10.f\n", f); /* prints only 8 correct digits */
printf("%10d\n", *(int*)&f); /* prints all digits correctly */
return 0;
}
$ gcc -Wall -O3 t.c
t.c: In function ‘main’:
t.c:7:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
$ ./a.out
2318926848
1326069764
我沒有看到你的“技巧”的精度增加,這取決於平台上浮點數的位代表(據我所知)。
這個帖子還有一些其他的“魔法花車”和一種生成它們的方法。
精度的限制是浮點表示,而不是printf()
它是一個錯誤的前提。
此外,單個精度浮點數只能保證精確到6位精度,因此“技巧”會欺騙自己; 在一般情況下它不會起作用。
如果你想要10位浮點數,那么你應該使用雙精度,這對於15位數是好的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.