GCE-Math(通用常量表达式数学)是一个模板化 C++ 库,支持数学函数的编译时计算。
特征:
constexpr格式编写,并且兼容 C++11/14/17/20。gcem::语法与 C++ 标准库 ( std:: ) 的语法相同。作者:基思·奥哈拉
该库得到积极维护,并且仍在扩展。功能列表包括:
abs 、 max 、 min 、 pow 、 sqrt 、 inv_sqrt 、ceil , floor , round , trunc , fmod ,exp 、 expm1 、 log 、 log1p 、 log2 、 log10等cos 、 sin 、 tanacos 、 asin 、 atan 、 atan2cosh 、 sinh 、 tanh 、 acosh 、 asinh 、 atanhlcm gcdfactorial , binomial_coefbeta 、 lbeta 、 lgamma 、 tgamma 、 lmgammaerf 、 erf_invincomplete_beta 、 incomplete_gammaincomplete_beta_inv 、 incomplete_gamma_inv完整文档可在线获取:
此处提供了该文档的 PDF 版本。
GCE-Math 是一个仅包含头文件的库,不需要任何其他库或实用程序(除了 C++11 兼容编译器之外)。只需使用以下方法将头文件添加到您的项目中:
# include " gcem.hpp "您可以使用 Conda 包管理器安装 GCE-Math。
conda install -c conda-forge gcem您还可以使用 CMake 从源安装该库。
# clone gcem from GitHub
git clone https://github.com/kthohr/gcem ./gcem
# make a build directory
cd ./gcem
mkdir build
cd build
# generate Makefiles and install
cmake .. -DCMAKE_INSTALL_PREFIX=/gcem/install/location
make install例如, /gcem/install/location可以是/usr/local/ 。
有两种构建测试套件的方法。在类似 Unix 的系统上,Makefile 在tests/下可用。
cd ./gcem/tests
make
./run_tests使用 CMake,选项GCEM_BUILD_TESTS=1生成构建测试套件所需的 Makefile。
cd ./gcem
mkdir build
cd build
cmake ../ -DGCEM_BUILD_TESTS=1 -DCMAKE_INSTALL_PREFIX=/gcem/install/location
make gcem_tests
cd tests
./exp.test您可以使用交互式 Jupyter 笔记本在线测试该库:
GCE-Math 函数被编写为带有constexpr说明符的 C++ 模板,其格式可能会让不熟悉基于模板的编程的用户感到困惑。
例如,高斯误差函数 ( erf ) 定义为:
template < typename T>
constexpr
return_t <T>
erf ( const T x) noexcept ;一组内部模板化constexpr函数将实现连分式扩展并返回return_t<T>类型的值。输出类型(' return_t<T> ')一般由输入类型决定,例如int 、 float 、 double 、 long double等;当T是整型时,输出将升级为return_t<T> = double ,否则return_t<T> = T 。对于std::is_integral未涵盖的类型,应使用重铸。
计算 10!:
# include " gcem.hpp "
int main ()
{
constexpr int x = 10 ;
constexpr int res = gcem::factorial (x);
return 0 ;
}检查 Clang 7.0.0 生成的汇编代码:
push rbp
mov rbp , rsp
xor eax , eax
mov dword ptr [ rbp - 4 ], 0
mov dword ptr [ rbp - 8 ], 10
mov dword ptr [ rbp - 12 ], 3628800
pop rbp
ret我们看到函数调用已被数值替换(10!= 3628800)。
类似地,计算某一点的 log Gamma 函数:
# include " gcem.hpp "
int main ()
{
constexpr long double x = 1.5 ;
constexpr long double res = gcem::lgamma (x);
return 0 ;
}汇编代码:
.LCPI0_0:
.long 1069547520 # float 1 . 5
.LCPI0_1:
.quad - 622431863250842976 # x86_fp80 - 0 . 120782237635245222719
.short 49147
.zero 6
main: # @main
push rbp
mov rbp , rsp
xor eax , eax
mov dword ptr [ rbp - 4 ], 0
fld dword ptr [ rip + .LCPI0_0 ]
fstp tbyte ptr [ rbp - 32 ]
fld tbyte ptr [ rip + .LCPI0_1 ]
fstp tbyte ptr [ rbp - 48 ]
pop rbp
ret