I am trying to make a C++ application calculate pi for me. I have tried to implement the Chudnovsky formula with no luck.
Here is my code:
#include <iostream>
#include <cmath>
long fac(long num) {
if (num == 1)
return 1;
return fac(num - 1) * num;
}
int main() {
using namespace std;
double pi;
for (long k = 0; k < 10; k++) {
pi += (pow(-1, k) * fac(6 * k) * (13591409 + (545140134 * k))) / (fac(3 * k) * pow(fac(k), 3) * pow(640320, 3 * k + 3/2));
}
pi *= 12;
cout << 1 / pi << endl;
system("pause");
return 0;
}
The goal of this was to have the program output 10 iterations of the Chudnovsky formula. Instead, I got this:
call of overloaded `pow(int, long int&)' is ambiguous
You never initialize
pi, so your code has undefined behaviour.Your
facfunction does not correctly handle0(fac(0)should be1).3/2evaluates to1(because it uses integer division, which truncates), and this makes your formula evaluate to the completely wrong answer.