The function below computes pi without relying on any libraries.
In addition, the type of its result is a template parameter.
The ueber-independent platform is a little stifled because it only works with fractional types with fixed precision - the calculated value should converge and remain constant for 2 iterations.
So, if you specify a class of rational accuracy or a floating point of arbitrary precision, which will automatically increase its accuracy as necessary, the call to this function will not end well.
#include <iostream> #include <iomanip> namespace golf { template <typename T> 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<double>(); } int main() { std::cout << std::setprecision(16) << golf::PI << std::endl; return 0; }
Christopher oicles
source share