Calculation of the Pi number with the Chudnovsky algorithm

So, here is some C ++ code for computing Pi using the Chudnovsky algorithm:

#include <iostream> #include <cmath> #include <iomanip> int fact(int digit) { int result = 1; for (int i=digit; i>1; i--) { result *= i; } return result; } int main() { long double pi = 0.0; int precision = 10; for ( int k=0; k<=precision; k++) { pi += ( pow(-1, k)*fact((6*k))*(13591409+545140134*k))/(fact(3*k)*pow(fact(k),3)*pow(640320, (3*k+1.5))); } pi = 1.0/(12*pi); std::cout<<std::setprecision(80)<<pi<<'\n'<<M_PI<<'\n'; } 

The problem is that this code returns only 15 right digits of the PI number, the other part is garbage ... when the precision variable is set to 12 or more, it returns -nan. Can anybody help me? TIA
EDIT: Ubuntu 12.10 x64, gcc 4.7.2

+4
source share
1 answer

Use double for the fact () return type, as well as the "result" variable inside fact ().

+1
source

All Articles