boost:math.constants

阳光穿透心脏的1/2处 2023-01-21 15:24 88阅读 0赞

概述

  • 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 } 2
  • root_three : 3 \sqrt[ ]{3 } 3
  • in_two : ln ⁡ 2 \ln{2} ln2

等等,这些都是编译期常数,没有运行时开销,所以运算效率很高

为了方便使用,math.constants库在名字空间boost::math里有定义了三个子名字空间,分别是float_constants、double_constants和long_double_constants,我们可以直接使用这些名字空间里对应的常数。

示例:

  1. #include <iostream>
  2. using std::cout;
  3. using std::endl;
  4. #include <boost/math/constants/constants.hpp>
  5. using namespace boost::math;
  6. //
  7. void case1()
  8. {
  9. cout << std::setprecision(64); //设置显示精度位64位
  10. auto a = float_constants::pi * 2 * 2;
  11. cout << "area \t\t= " << a << endl;
  12. using namespace double_constants;
  13. auto x = root_two * root_three;
  14. cout << "root 2 * 3 \t= " << x << endl;
  15. cout << "root pi \t= " << root_pi << endl;
  16. cout << "pi pow e \t= " << pi_pow_e << endl;
  17. }
  18. int main()
  19. {
  20. case1();
  21. }

在这里插入图片描述

高级用法

math.constants库模仿C++14里的模板变量特性,在boost::math::constants里定义了同名的函数模板,可以不必使用名字空间直接指定数值类型。如果我们使用另一个数学库——高精度数据库boost.multiprecision,那么就可以获得比long double还要高的精确度:

  1. #include <iostream>
  2. using namespace std;
  3. #include <boost/math/constants/constants.hpp>
  4. using namespace boost::math;
  5. #include <boost/multiprecision/cpp_dec_float.hpp>
  6. void case1()
  7. {
  8. using namespace constants;
  9. typedef decltype(pi<float>) pi_t;
  10. assert(is_function<pi_t>::value);
  11. assert(pi<float>() == float_constants::pi); // 函数模板获取pi值
  12. assert(pi<double>() == double_constants::pi); // double精度
  13. typedef boost::multiprecision::cpp_dec_float_100 float_100;
  14. cout << setprecision(100) // 设置精度位100位
  15. << pi<float_100>() << endl; // 100位小数浮点数
  16. }
  17. int main()
  18. {
  19. case1();
  20. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,88人围观)

还没有评论,来说两句吧...

相关阅读