C ++ Chudnovskiy formula for Pi

I am trying to make a C ++ application to calculate pi for me. I tried to implement the Chudnovsky formula without 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 purpose of this was for the program to output 10 iterations of the Chudnovsky formula. Instead, I got the following:

 call of overloaded `pow(int, long int&)' is ambiguous 
+1
source share
3 answers

You never initialize pi , so your code has undefined behavior.

Your fac function fac not handle 0 correctly ( fac(0) must be 1 ).

3/2 evaluates to 1 (because it uses integer division, which is truncated), and this makes your evaluation formula a completely wrong answer.

+8
source

You almost certainly want to do all the math in doubles to avoid a lot of time killing conversions. You probably also want to use the iterative implementation of fac instead of the recursive one (not that recursion will be a big problem, but it is a prime example of when recursion should be avoided because it doesn't get anything). Of course, you also need to initialize pi , as others have already pointed out.

 #include <iostream> #include <iomanip> #include <cmath> double fac(double num) { double result = 1.0; for (double i=2.0; i<num; i++) result *= i; return result; } int main() { using namespace std; double pi=0.0; for (double k = 0.0; k < 10.0; k++) { pi += (pow(-1.0,k) * fac(6.0 * k) * (13591409.0 + (545140134.0 * k))) / (fac(3.0 * k) * pow(fac(k), 3.0) * pow(640320.0, 3.0 * k + 3.0/2.0)); } pi *= 12.0; cout << setprecision(15) << 1.0 / pi << endl; return 0; } 
+3
source

pow (-1, k) is inefficient, as it is a direct translation from a mathematical formula to code.

Use this instead:

  (k%2==1?-1.0:1.0)*fac(... 

Edit:

Also, your face code is also not optimal.

+1
source

All Articles