哪些单精度浮点数需要 9 位有效十进制数字才能明确表示十进制数?

T. *_*zke 3 floating-point precision

我在这篇关于单精度浮点数的维基百科文章中发现了以下声明https://en.wikipedia.org/wiki/Single-precision_floating-point_format

如果将 IEEE 754 单精度数转换为至少有 9 位有效数字的十进制字符串,然后再转换回单精度表示,则最终结果必须与原始数匹配。

我试图找到单精度浮点数的例子,它们实际上需要 9 个有效的十进制数字,并且还没有明确的只有 8 个有效数字并且没有找到任何,例如通过在 gdb 调试器中打印浮点值或通过尝试将不同的值转换为八度的单精度,但还没有发现需要超过 8 个十进制数字才能具有与其直接相邻浮点值不同的十进制表示的示例。

问题是,实际上是否存在需要 9 位十进制数字的单精度(32 位)浮点值,或者这只是一个永远不需要的安全上限。你能举一个单精度浮点值的例子,当它转换为只有 8 个有效十进制数字,然后转换回二进制浮点表示时,它的值与原始浮点数不同。

T. *_*zke 5

32 位浮点数以 32 位存储,这意味着不能有超过大约 40 亿个不同值。计算机的速度足以遍历所有数字,因此,对 32 位浮点数的蛮力搜索可以在可接受的时间内自动执行此操作,并测试所有可能的数字是否转换为只有 8 个有效十进制数字加上从字符串到单精度浮点表示的逆转换会改变值。

以下简短的 C++ 程序对所有正浮点值执行此操作:

#include <cstdio>
#include <cmath>
#include <limits>
#include <cinttypes>

int main(int argc, char**argv) {
  // Test if conversion with /precision/ significant decimal digit is enough
  int precision = 8;

  // Can override precision = 8 with a command line parameter
  if (argc > 1) {
    precision = strtol(argv[1], nullptr, 0);
    if (precision < 1 || precision > 50) {
      printf("Error: precision should be between 1 and 50, got %d.\n",
             precision);
      exit(1);
    }
  }

  // Buffer length of character buffers to store string representations of
  // floating point numbers with /precision/ significant digits.  /buflen/ is
  // larger than /precision/ because it also needs to store leading zeros,
  // decimal point, sign, scientific notation exponents, and terminating \0.
  const int buflen = precision + 10;

  // storage for current number converted to string with 8 decimal digits
  char str[buflen] = "";

  // shorthands for maxfloat and infinity
  const float maxfloat = std::numeric_limits<float>::max();
  const float inf = std::numeric_limits<float>::infinity();

  // Count the number of times where /precision/ was not sufficient
  uint64_t num_clashes_found = 0;

  // Count all tested floats
  uint64_t num_floats_tested = 0;

  // loop over all positive single precision floating point numbers
  for (float f = 0.0f;               // start with zero
       f <= maxfloat;                // iterate up to and including maxfloat
       ++num_floats_tested,          // count the number of all tested floats
       f = nextafterf(f, inf))       // increment f to next larger float value 
  {
    // convert number to string with /precision/ significant decimal digits
    int numprintedchars = snprintf(str, buflen, "%.*g", precision, f);

    // If string buffer is not long enough to store number as string with
    // /precision/ significant digits, then print warning and terminate program
    if (numprintedchars >= buflen) {
      printf("Buffer length %d is not enough to store \"%.*g\", should"
             " be at least %d\n", buflen, precision, f, numprintedchars+1);
      exit(1);
    }

    // convert the string back to float
    float float_from_string = strtof(str,nullptr);

    // Compare the value
    if (f != float_from_string) {
      printf("%.*g converts to \"%s\" which reads back as %.*g.\n",
             precision+1, f, str, precision+1, float_from_string);
      ++num_clashes_found;
    }
  }
  printf("Found %" PRIu64" clashes when using %d significant decimal digits.\n",
         num_clashes_found, precision);
  printf("Total number of tested floats is %" PRIu64", i.e. with %d significant"
         " decimal digits, we get clashes in %g%% of all numbers.\n",
         num_floats_tested, precision,
         100.0 / num_floats_tested * num_clashes_found);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

该程序需要大约 20 分钟来遍历所有正单精度浮点数。

它找到的一个示例数字是 0.111294314f。当转换为具有 8 位有效数字的十进制字符串时,结果为“0.11129431”。下一个较小的单精度浮点数是 0.111294307f,当转换为只有 8 位有效数字的字符串时,它具有相同的十进制表示。

总的来说,程序计算出大约有 21.4 亿个正浮点数,但其中只有大约 3200 万个需要 9 位有效十进制数字才能明确表示。这对应于需要 9 位数字的所有数字的 1.5%,这就解释了为什么手动测试不太可能找到它们:

很明显,人们会手动测试以数字 1 开头的十进制表示形式的浮点值,因为对于这些浮点值,与以数字 9 开头的非常相似的值相比,前导 1 需要一个更有效的十进制数字。但是,还有 10 的幂,没有浮点值转换为十进制 1.xxx * 10^yy 存在,实际上需要 9 位有效数字。这些 10 的幂(8 个有效数字总是足够的)是(给出 10 的指数,上面命名为 yy):-34、-31、-21、-18、-15、-12、-09、-06、-05 、-03、+00、+07、+08、+10、+13、+16、+19、+22、+25、+28。如果碰巧手动测试接近这些 10 次幂中的任何一个的值,则不会发现任何阳性结果。这包括 10^0,即接近 1.0 的值,