我需要任意(但固定)精度的pi(3.1415 ...)boost::multiprecision.
如本答案中boost::math::constants所指出的,常量仅定义为固定的位数,因此我需要自己计算.
因为我经常使用这个数字并且数字位数很多,所以我想在运行时只计算一次.拥有它的简单而快捷的方法是什么?
我想过要用
typedef number<cpp_dec_float<PRECISION> > mpfloat; // PRECISION is compile time.
const int PI = atan(mpfloat(1))*4;
Run Code Online (Sandbox Code Playgroud)
但我不确定这是一个常见的习语.
在c ++ 14中,您可以使用模板变量(http://en.cppreference.com/w/cpp/language/variable_template).
请注意,您已经拥有了所需的内容
#include <boost/multiprecision/detail/default_ops.hpp>
Run Code Online (Sandbox Code Playgroud)
该标题最终包含constants.hpp哪个定义template <class T> const T& get_constant_pi().
这是模板变量的c ++ 03习惯用法(因为它存储了函数本地静态结果值).
calc_pi 具有硬编码的前1100个数字,其余部分通过优化的公式计算(如果需要).
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/detail/default_ops.hpp>
#include <boost/multiprecision/number.hpp>
#include <iostream>
namespace {
namespace bmp = boost::multiprecision;
template <int N> bmp::number<bmp::cpp_dec_float<N> > const my_const_pi
= bmp::default_ops::get_constant_pi<bmp::cpp_dec_float<N> >();
}
int main() {
std::cout << std::setprecision(50) << my_const_pi<50> << "\n";
std::cout << std::setprecision(5000) << my_const_pi<5000> << "\n";
}
Run Code Online (Sandbox Code Playgroud)
打印
3.1415926535897932384626433832795028841971693993751 3.