I know that you can use:
#define _USE_MATH_DEFINES
and then:
M_PI
to get the constant pi. However, if I r
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;
}