C Program to Calculate Value of PI using Leibniz Formula

The Leibniz formula is an infinite series method of calculating Pi. The formula is a very simple way of calculating Pi, however, it takes a large amount of iterations to produce a low precision value of Pi.

Leibniz formula:
π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
Or, π = 4 ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... )

In this program we first read number of term to consider in series from user and then apply Leibniz formula to caluclate value of Pi.

This C program calculates value of Pi using Leibniz formula.

C Source Code: Calculation of Pi using Leibniz Formula


#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
 long int i, n;
 double sum=0.0, term, pi;
 
 printf("Enter number of terms: ");
 scanf("%ld", &n);

 /* Applying Leibniz Formula */
 for(i=0;i< n;i++)
 {
  term = pow(-1, i) / (2*i+1);
  sum += term;
 }
 pi = 4 * sum;

 printf("\nPI = %.6lf", pi);
 
 return 0;
}

Output

Enter number of terms: 1000000

PI = 3.141592
To get more accurate result use higher value of n.