我正在运行物理实验模拟,因此我需要非常高的浮点精度(超过 16 位)。我使用 Boost.Multiprecision,但是无论我尝试什么,我都无法获得高于 16 位的精度。我使用 C++ 和 eclipse 编译器运行模拟,例如:
#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.12345678912345678379658409085095627233386039733887
^
但应该是:
0.123456789123456789123456789
如您所见,在 16 位数字之后是不正确的。为什么?
最佳答案
您的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
编译器不使用任意精度的浮点文字,而是使用具有有限精度的 IEEE-754 doubles。在这种情况下,最接近您所写数字的 double
是:
0.1234567891234567837965840908509562723338603973388671875
并将它打印到小数点后 50 位确实给出了您正在观察的输出。
您想要的是从字符串构造任意精度 float (demo):
#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
关于c++ - 使用 boost lib 的更高精度 float (高于 16 位数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494620/