boost:math.constants
概述
- math.constants库提供了 π \pi π、 e e e、 2 \sqrt[ ]{2 } 2 等常用的数学常数,支持float、double、long double精度,而且还支持自定义类型以获得更高的精度
math.constants库位于名字空间
boost::math
,需要包含头文件<boost/math/constants/constants.hpp>
,即:include
using namespace boost::math;
基本用法
math.constants库定义了很多科学计算中用到的常数,精度高达小数点后100位,比较常用的有:
pi
: 圆周率 π \pi πe
: 自然对数的底root_tow
: 2 \sqrt[ ]{2 } 2root_three
: 3 \sqrt[ ]{3 } 3in_two
: ln 2 \ln{2} ln2
等等,这些都是编译期常数,没有运行时开销,所以运算效率很高
为了方便使用,math.constants库在名字空间boost::math里有定义了三个子名字空间,分别是float_constants、double_constants和long_double_constants,我们可以直接使用这些名字空间里对应的常数。
示例:
#include <iostream>
using std::cout;
using std::endl;
#include <boost/math/constants/constants.hpp>
using namespace boost::math;
//
void case1()
{
cout << std::setprecision(64); //设置显示精度位64位
auto a = float_constants::pi * 2 * 2;
cout << "area \t\t= " << a << endl;
using namespace double_constants;
auto x = root_two * root_three;
cout << "root 2 * 3 \t= " << x << endl;
cout << "root pi \t= " << root_pi << endl;
cout << "pi pow e \t= " << pi_pow_e << endl;
}
int main()
{
case1();
}
高级用法
math.constants库模仿C++14里的模板变量特性,在boost::constants里定义了同名的函数模板,可以不必使用名字空间直接指定数值类型。如果我们使用另一个数学库——高精度数据库boost.multiprecision,那么就可以获得比long double还要高的精确度:
#include <iostream>
using namespace std;
#include <boost/math/constants/constants.hpp>
using namespace boost::math;
#include <boost/multiprecision/cpp_dec_float.hpp>
void case1()
{
using namespace constants;
typedef decltype(pi<float>) pi_t;
assert(is_function<pi_t>::value);
assert(pi<float>() == float_constants::pi); // 函数模板获取pi值
assert(pi<double>() == double_constants::pi); // double精度
typedef boost::multiprecision::cpp_dec_float_100 float_100;
cout << setprecision(100) // 设置精度位100位
<< pi<float_100>() << endl; // 100位小数浮点数
}
int main()
{
case1();
}
还没有评论,来说两句吧...