请考虑在std::exp 数字学库中的标头卡马奇中定义的C++。现在,请考虑C++标准库的实现,比如libstdc++。
考虑到,计算初等函数的算法有,如计算指数函数的算术几何平均迭代算法算法和其他三种表示这里的算法;
如果可能的话,你能说出在libstdc++中用来计算指数函数的具体算法吗?
PS:恐怕我找不到包含std::exp实现的正确的tarball或理解相关的文件内容。
发布于 2018-04-21 20:43:24
它根本不使用任何复杂的算法。请注意,std::exp只为非常有限的类型定义:float、double和long double +任何可转换到double的整数类型。这就使得没有必要实施复杂的数学。
目前,它使用内置的__builtin_expf,可以从源代码中进行验证。这将编译为我的机器上对expf的调用,这是来自glibc的对libm的调用。让我们看看我们在他们的源代码中发现了什么。当我们搜索expf时,我们发现这在内部调用了__ieee754_expf,这是一个依赖于系统的实现。i686和x86_64只包含一个glibc/sysdeps/ieee754/flt-32/e_expf.c,它最终给了我们一个实现(简化为简洁,即外观进入源头 )。
它基本上是浮子的三次多项式逼近:
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;
}类似地,对于128位long double,它是一个7阶近似,对于double,他们使用的是更复杂的算法,我现在无法理解。
https://stackoverflow.com/questions/49960020
复制相似问题