问题描述
我正在模拟物理实验,所以我需要非常高的浮点精度(超过 16 位).我使用 Boost.Multiprecision,但是无论我尝试什么,我都无法获得高于 16 位的精度.我用C++和eclipse编译器运行模拟,例如:
I am running a simulation of physical experiments, so I need really high floating point precision (more than 16 digits). I use Boost.Multiprecision, however I can't get a precision higher than 16 digits, no matter what I tried. I run the simulation with C++ and eclipse compiler, for example:
#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 位数字之后是不正确的.为什么?
As you can see, after 16 digits it is incorrect. Why?
推荐答案
您的问题在这里:
cpp_dec_float_50 my_num = cpp_dec_float_50(0.123456789123456789123456789);
^ // This number is a double!
编译器不使用任意精度的浮点文字,而是使用 IEEE-754 doubles,它们具有有限精度.在这种情况下,与您所写数字最接近的 double
是:
The compiler does not use arbitrary-precision floating point literals, and instead uses IEEE-754 doubles, which have finite precision. In this case, the closest double
to the number you have written is:
0.1234567891234567837965840908509562723338603973388671875
并将其打印到小数点后 50 位确实可以提供您正在观察的输出.
And printing it to the 50th decimal does indeed give the output you are observing.
您想要的是从字符串构造任意精度的浮点数(演示)::>
What you want is to construct your arbitrary-precision float from a string instead (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
这篇关于使用 boost lib 的更高精度浮点数(高于 16 位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!