What is the fastest way to get the value of π?

后端 未结 23 1795
自闭症患者
自闭症患者 2020-11-28 00:33

I\'m looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I\'m using ways that don\'t involve using #define constan

23条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 01:00

    The Chudnovsky algorithm is pretty fast if you don't mind performing a square root and a couple inverses. It converges to double precision in just 2 iterations.

    /*
        Chudnovsky algorithm for computing PI
    */
    
    #include 
    #include 
    using namespace std;
    
    double calc_PI(int K=2) {
    
        static const int A = 545140134;
        static const int B = 13591409;
        static const int D = 640320;
    
        const double ID3 = 1./ (double(D)*double(D)*double(D));
    
        double sum = 0.;
        double b   = sqrt(ID3);
        long long int p = 1;
        long long int a = B;
    
        sum += double(p) * double(a)* b;
    
        // 2 iterations enough for double convergence
        for (int k=1; k
                                                            
提交回复
热议问题