Higher floating point precision using boost lib (over 16 digits)

I run a simulation of physical experiments, so I need really high precision with a floating point (more than 16 digits). I am using Boost.Multiprecision, however I cannot get accuracy above 16 digits, no matter what I tried. I run the simulation using the C ++ compiler and eclipse, 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; } 

Output:

 0.12345678912345678379658409085095627233386039733887 ^ 

But it should be:

 0.123456789123456789123456789 

As you can see, after 16 digits this is not true. Why?

+5
source share
2 answers

Your problem is here:

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

The compiler does not use arbitrary precision floating point literals and instead uses IEEE-754 doubles that have finite precision. In this case, the closest double to the number you wrote:

 0.1234567891234567837965840908509562723338603973388671875 

And printing it in the 50th decimal decade really gives the result that you are observing.

What you want is to build an arbitrary precision plugin from a string ( 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; } 

Output:

 0.123456789123456789123456789 
+11
source

The problem is that the C ++ compiler converts numbers to double parts when compiling (I also found out about this some time ago). You must use special functions to process more decimal points. See the Boost documentation or other answers here on SO for examples.

However, it is almost impossible that there is a real need for such high precision. If you lose accuracy, you should consider other floating point algorithms instead of blindly increasing the number of decimal places.

+2
source

Source: https://habr.com/ru/post/1235098/


All Articles