C++ calculating more precise than double or long double

后端 未结 2 620
有刺的猬
有刺的猬 2020-12-01 18:47

I\'m teaching myself C++ and on this practice question it asks to write code that can calculate PI to >30 digits. I learned that double / long double are both 16 digits prec

相关标签:
2条回答
  • 2020-12-01 19:11

    You will need to perform the calculation using some other method than floating point. There are libraries for doing "long math" such as GMP.

    If that's not what you're looking for, you can also write code to do this yourself. The simplest way is to just use a string, and store a digit per character. Do the math just like you would do if you did it by hand on paper. Adding numbers together is relatively easy, so is subtracting. Doing multiplication and division is a little harder.

    For non-integer numbers, you'll need to make sure you line up the decimal point for add/subtract...

    It's a good learning experience to write that, but don't expect it to be something you knock up in half an hour without much thought [add and subtract, perhaps!]

    0 讨论(0)
  • 2020-12-01 19:15

    You can use quad math, builtin type __float128 and q/Q suffixes in GCC/clang.

    #include <stdio.h>
    
    #include <quadmath.h>
    
    int main ()
    {
      __float128 x = strtoflt128("1234567891234567891234567891234566", nullptr);
      auto y = 1.0q;
      printf("%.Qf", x + y); // there is quadmath_snprintf, but this also works fine
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题