Best platform independent pi constant?

后端 未结 2 504
温柔的废话
温柔的废话 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:14

    Meeting C++ has an article on the different options for generating pi: C++ & π they discuss some of the options, from cmath, which is not platform independent:

    double pi = M_PI;
    std::cout << pi << std::endl;
    

    and from boost:

    std::cout << boost::math::constants::pi() << std::endl
    

    and using atan, with constexpr removed since as SchighSchagh points out that is not platform independent:

     double const_pi() { return std::atan(1)*4; }
    

    I gathered all the methods into a live example:

    #include 
    #include 
    #include 
    
    double piFunc() { return std::atan(1)*4; }
    
    int main()
    {
        double pi = M_PI;
        std::cout << pi << std::endl;
        std::cout << boost::math::constants::pi() << std::endl ;
        std::cout << piFunc() << std::endl;
    }
    

    C++2a pi_v

    In C++2a we should get pi_v:

    #include 
    #include 
    
    int main() {
         std::cout<< std::numbers::pi_v <<"\n";
    }
    

提交回复
热议问题