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

后端 未结 2 1180
刺人心
刺人心 2020-12-11 05:58

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 p

2条回答
  •  借酒劲吻你
    2020-12-11 06:15

    Your issue 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, which have finite precision. In this case, the closest double to the number you have written is:

    0.1234567891234567837965840908509562723338603973388671875
    

    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 
    #include 
    #include 
    #include 
    
    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::digits10);
        std::cout << my_num << std::endl;
    }
    

    Output:

    0.123456789123456789123456789
    

提交回复
热议问题