Best platform independent pi constant?

后端 未结 2 515
温柔的废话
温柔的废话 2020-12-18 23:39

I know that you can use:

#define _USE_MATH_DEFINES

and then:

M_PI

to get the constant pi. However, if I r

2条回答
  •  难免孤独
    2020-12-19 00:00

    The function below calculates pi without relying on any libraries at all.

    Also, the type of its result is a template parameter.

    Platform ueber-independence is stifled a bit because it only works with fixed-precision fractional types -- the calculated value needs to converge and remain constant over 2 iterations.

    So if you specify some kind of arbitrary-precision rational or floating-point class which will automatically increase its precision as needed, a call to this function will not end well.

    #include 
    #include 
    
    namespace golf {
        template  inline T calc_pi() {
            T sum=T(0), k8=T(0), fac=T(1);
            for(;;) {
                const T next = 
                    sum + fac*(T(4)/(k8+T(1))-T(2)/(k8+T(4))-T(1)/(k8+T(5))-T(1)/(k8+T(6)));
                if(sum == next) return sum;
                sum=next;
                fac /= T(16);
                k8  += T(8);
        }   }
        static const auto PI = calc_pi();
    }
    
    int main() {
        std::cout << std::setprecision(16) << golf::PI << std::endl;
        return 0;
    }
    

提交回复
热议问题