使用boost-lib的更高精度浮点(高于16位)

higher precision floating point using boost lib (higher then 16 digits)

本文关键字:高于 16位 boost-lib 高精度 使用      更新时间:2023-10-16

我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过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双精度。在这种情况下,最接近您所写数字的double是:

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

问题是C++编译器在编译时会将数字转换为双精度(我不久前也学到了这一点)。你必须使用特殊的函数来处理更多的小数点。有关示例,请参阅Boost文档或SO上的其他答案。

也就是说,几乎不可能真正需要如此高的精度。如果你正在失去精度,你应该考虑其他浮点算法,而不是盲目地增加小数位数。