A question about floating-point precision in Go让我想知道C如何处理这个问题.
使用C中的以下代码:
float a = 0.1;
是否具有最接近的IEEE 754二进制表示:
00111101110011001100110011001101 (Decimal: 0.10000000149011612)
或者只是将它裁剪成:
00111101110011001100110011001100 (Decimal: 0.09999999403953552)
或者根据编译器/平台的不同而不同?
解决方法
允许实现(或者甚至多一个):
For decimal floating constants,and also for hexadecimal floating constants when FLT_RADIX is not a power of 2,the result is either the nearest representable value,or the larger or smaller representable value immediately adjacent to the nearest representable value,chosen in an implementation-defined manner.
(C11,§6.4.4.2/ 3)
从C99开始,我们已经有了十六进制浮点常量,因此您可以精确指定所需的位(假设实现提供了二进制浮点:)),所以您可以说,例如:
float a = 0x1.99999Ap-4;
对于IEEE 754 32位浮点数:
#include <stdio.h> int main() { float a = 0.1; float low = 0x0.1999999p0; float best = 0x0.199999ap0; float high = 0x0.199999bp0; printf("a is %.6a or %.16f,which is either %.16f,%.16f or %.16f\n",a,low,best,high); return 0; }