C++ 使用boost库的高精度浮点(高于16位)
我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过16位)。我使用Boost.Multiprecision,但是无论我怎么做,我都无法获得高于16位的精度。我用C++和Eclipse编译器运行模拟,例如:C++ 使用boost库的高精度浮点(高于16位),c++,boost,precision,multiprecision,C++,Boost,Precision,Multiprecision,我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过16位)。我使用Boost.Multiprecision,但是无论我怎么做,我都无法获得高于16位的精度。我用C++和Eclipse编译器运行模拟,例如: #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> #include
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
using boost::multiprecision::cpp_dec_float_50;
void main()
{
cpp_dec_float_50 my_num= cpp_dec_float_50(0.123456789123456789123456789);
std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);
std::cout << my_num << std::endl;
}
但它应该是:
0.123456789123456789123456789
0.123456789123456789123456789
如您所见,16位数字之后是不正确的。为什么? < P>问题是编译时C++编译器将数字转换为双倍(我也是刚才)。您必须使用特殊函数来处理更多的小数点。有关示例,请参见此处的或其他 也就是说,几乎不可能真正需要如此高的精度。如果你正在降低精度,你应该考虑其他浮点算法,而不是盲目增加小数。 < P>你的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
编译器不使用任意精度浮点文本,而是使用具有有限精度的IEEE-754双精度。在这种情况下,与您所写数字最接近的双精度:
0.1234567891234567837965840908509562723338603973388671875
将其打印到第50位小数确实给出了您正在观察的输出
您想要的是从字符串()构造任意精度浮点:
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
#include <limits>
using boost::multiprecision::cpp_dec_float_50;
int main() {
cpp_dec_float_50 my_num = cpp_dec_float_50("0.123456789123456789123456789");
std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);
std::cout << my_num << std::endl;
}
0.123456789123456789123456789