Which algorithm is used to compute exponential functions the GNU C++ Standard Library?(GNU C++标准库使用哪种算法来计算指数函数?)
问题描述
请考虑在C++numerics库的头cmath中定义std::exp。现在,请考虑C++标准库的实现,比如libstdc++。考虑有各种算法计算初等函数,如arithmetic-geometric mean iteration algorithm计算指数函数和其他三种算法here;
如果可能,请您说出libstdc++中用来计算指数函数的特定算法好吗?
PS:恐怕我既找不到包含std::exp实现的正确tarball,也无法理解相关的文件内容。
推荐答案
它根本不使用任何复杂的算法。请注意,std::exp
仅为非常有限的类型定义:float
、double
和long double
+任何可强制转换为double
的整型。这样就不需要进行复杂的数学运算了。
目前,它使用的内置__builtin_expf
可以从源代码中验证。这将编译为在我的机器上调用expf
,这是来自glibc
的对libm
的调用。让我们看看我们在他们的source code中找到了什么。当我们搜索expf
时,我们发现它在内部调用__ieee754_expf
,这是一个依赖于系统的实现。I686和x86_64都只包含一个glibc/sysdeps/ieee754/flt-32/e_expf.c
,它最终为我们提供了一个实现(为简洁起见,外观into the sources
它基本上是浮点数的三次多项式逼近:
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
,它是一个order 7 approximation,而对于double
,他们使用的more complicated algorithm我现在无法理解。
这篇关于GNU C++标准库使用哪种算法来计算指数函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GNU C++标准库使用哪种算法来计算指数函数?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01