使用大浮点数的计算是否不如使用小浮点数的计算准确

are computations with large floats less accurate then with small floats

这个说法正确吗? :

Computations with large numbers is less accurate due to the logarithmic distribution of floating point numbers on the computer.

所以这意味着使用 1 左右的值进行计算比使用 1e20 缩放每个数字的相同计算更准确(因为舍入误差)?

简答:

是的,这个说法是正确的,较大的浮点数比较小的浮点数不够精确。

详情:

浮点数具有分配给 mantissa 的固定位数。如果表示的数字需要的位数多于尾数中的位数,那么它将被四舍五入。因此可以更精确地表示更小的数字。

为了使这个更具体,我编写了以下程序,将越来越小的值添加到一个大的浮点数和一个小的浮点数。另外为了显示差异,我包括了一个没有舍入的双精度浮点数。但是,如果尾数更大,双精度会遇到同样的问题。

#include <stdio.h>

int main() {
  float large_float, small_float, epsilon;
  double large_double, small_double;

  large_float = 1 << 20;
  small_float = 1;
  epsilon = 0.1;

  large_double = large_float;
  small_double = small_float;

  printf("large_float\t large_double\t small_float\t small_double\t epsilon\n");

  for(int i = 0; i < 10; i++) {
    printf("%f\t %f\t %f\t %f\t %f\n", large_float, large_double,small_float, small_double, epsilon);
    large_float += epsilon;
    large_double += epsilon;
    small_float += epsilon;
    small_double += epsilon;
    epsilon /= 2;        
  }

  return 0;
}

运行 该程序产生以下输出:

large_float      large_double    small_float     small_double    epsilon
1048576.000000   1048576.000000  1.000000        1.000000        0.100000
1048576.125000   1048576.100000  1.100000        1.100000        0.050000
1048576.125000   1048576.150000  1.150000        1.150000        0.025000
1048576.125000   1048576.175000  1.175000        1.175000        0.012500
1048576.125000   1048576.187500  1.187500        1.187500        0.006250
1048576.125000   1048576.193750  1.193750        1.193750        0.003125
1048576.125000   1048576.196875  1.196875        1.196875        0.001563
1048576.125000   1048576.198438  1.198437        1.198438        0.000781
1048576.125000   1048576.199219  1.199219        1.199219        0.000391
1048576.125000   1048576.199609  1.199609        1.199609        0.000195

如您所见,large_float 值不如 small_float 精确,这也会导致最终结果不太准确。