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
In the interests of completeness, a C++ template version, which, for an optimised build, will compute an approximation of PI at compile time, and will inline to a single value.
#include
template
struct sign
{
enum {value = (I % 2) == 0 ? 1 : -1};
};
template
struct pi_calc
{
inline static double value ()
{
return (pi_calc::value () + pi_calc::value ()) / 2.0;
}
};
template
struct pi_calc<0, J>
{
inline static double value ()
{
return (sign::value * 4.0) / (2.0 * J + 1.0) + pi_calc<0, J-1>::value ();
}
};
template<>
struct pi_calc<0, 0>
{
inline static double value ()
{
return 4.0;
}
};
template
struct pi
{
inline static double value ()
{
return pi_calc::value ();
}
};
int main ()
{
std::cout.precision (12);
const double pi_value = pi<10>::value ();
std::cout << "pi ~ " << pi_value << std::endl;
return 0;
}
Note for I > 10, optimised builds can be slow, likewise for non-optimised runs. For 12 iterations I believe there are around 80k calls to value() (in the absence of memoisation).