6

我正在运行物理实验的模拟,所以我需要非常高的浮点精度(超过 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 位之后它是不正确的。为什么?

4

2 回答 2

13

你的问题在这里:

cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
                                            ^ // This number is a double!

编译器不使用任意精度的浮点文字,而是使用具有有限精度的 IEEE-754 doubles 。在这种情况下,最接近double您所写数字的是:

0.1234567891234567837965840908509562723338603973388671875

并将其打印到小数点后 50 位确实会给出您正在观察的输出。

你想要的是从一个字符串构造你的任意精度浮点数(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
于 2015-11-03T08:53:00.500 回答
2

问题是 C++ 编译器在编译时将数字转换为双精度数(我前段时间也学过)。您必须使用特殊功能来处理更多小数点。有关示例,请参见此处的Boost 文档或其他答案。

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

于 2015-11-03T08:52:33.657 回答