请考虑std::exp标头中定义cmath in C++ numerics图书馆。现在,请考虑 C++ 标准库的实现,例如libstdc++ 库.
考虑到有各种算法计算初等函数,例如算术几何平均迭代算法计算指数函数和其他三个函数here;
您能否说出用于计算指数函数的特定算法libstdc++ 库, 如果可能的话?
PS:恐怕我无法确定包含 std::exp 实现的正确 tarball 或理解相关文件内容。
它根本不使用任何复杂的算法。注意std::exp
仅为非常有限的类型定义:float
, double
and long double
+ 任何可转换为的 Integral 类型double
。这使得没有必要执行复杂的数学运算。
目前,它使用内置的__builtin_expf
从源码中可以验证。这编译为对expf
在我的机器上这是一个调用libm
来自(哪里glibc
。让我们看看我们在他们身上发现了什么源代码。当我们寻找expf
我们发现这在内部调用__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;
}
同样,对于 128 位long double
, 这是一个7 阶近似并为double
他们使用更复杂的算法我现在无法理解。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)