GNU C++ 标准库使用哪种算法来计算指数函数?

Her*_*eer 6 c++ gnu exponentiation libstdc++

请考虑C++数字库中头文件cmath中定义的std::exp。现在,请考虑 C++ 标准库的实现,例如libstdc++

考虑到有多种算法来计算初等函数,例如算术几何平均迭代算法来计算指数函数以及此处显示的其他三种算法;

如果可能的话,您能否说出用于计算libstdc++中指数函数的特定算法?

PS:恐怕我无法确定包含 std::exp 实现的正确 tarball 或理解相关文件内容。

Wor*_*der 10

它根本不使用任何复杂的算法。请注意,std::exp仅针对非常有限数量的类型定义:floatdouble+long double任何可转换为 的 Integral 类型double。这使得没有必要执行复杂的数学运算。

目前,它使用内置的__builtin_expf,可以从源代码中验证。这会编译为对我机器上的调用expf,该调用libm来自glibc. 让我们看看在他们的源代码中发现了什么。当我们搜索时,expf我们发现 this 内部调用了__ieee754_expf一个依赖于系统的实现。i686 和 x86_64 都只包含一个glibc/sysdeps/ieee754/flt-32/e_expf.c最终为我们提供了一个实现(为简洁起见,请查看源代码

它基本上是浮点数的 3 阶多项式近似:

static inline uint32_t
top12 (float x)
{
  return asuint (x) >> 20;
}

float
__expf (float x)
{
  uint64_t ki, t;
  /* double_t for better performance on targets with FLT_EVAL_METHOD==2.  */
  double_t kd, xd, z, r, r2, y, s;

  xd = (double_t) x;
  // [...] skipping fast under/overflow handling

  /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k.  */
  z = InvLn2N * xd;

  /* Round and convert z to int, the result is in [-150*N, 128*N] and
     ideally ties-to-even rule is used, otherwise the magnitude of r
     can be bigger which gives larger approximation error.  */
  kd = roundtoint (z);
  ki = converttoint (z);
  r = z - kd;

  /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
  t = T[ki % N];
  t += ki << (52 - EXP2F_TABLE_BITS);
  s = asdouble (t);
  z = C[0] * r + C[1];
  r2 = r * r;
  y = C[2] * r + 1;
  y = z * r2 + y;
  y = y * s;
  return (float) y;
}
Run Code Online (Sandbox Code Playgroud)

同样,对于 128 位long double,它是7 阶近似,因为double它们使用了我现在无法理解的更复杂的算法。

  • 我在之前的评论中弄错了时间表。Glibc 2.26 版本来自 2017 年 8 月,并且具有旧算法(与此答案中发布的算法不同),但版本 2.27(来自 2018 年 2 月 1 日)使用上面介绍的算法。不过,如果您的 glibc 不是最新的,那么您的机器使用的算法可能会有所不同。 (2认同)