c++ - 使用 boost lib 的更高精度 float (高于 16 位数字)

标签 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 <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/

相关文章:

c++ - 将内存清理器与 libstdc++ 一起使用

c++ - 下面的类继承如何设计?

Python float 精度 float

math - float 学有问题吗?

JavaScript浮点精度问题

c++ - 计算for循环c++中的出现次数

c++ - 初始化 boost::shared_ptr 的正确方法

c++ - Boost Windows 程序是否可以移植到其他 Windows 系统?

c++ - 嵌入式 Python : Getting func obj from imported module

c++ - 虚拟构造函数习语和工厂设计