Approximation of Pi by using the Monte Carlo method

Nikos Mouzakitis
2 min readMar 4, 2019

By using random inputs to solve problems, the Monte Carlo method has a wide variety of applications. The presented implementation is using the C programming language to approximate the value of π(pi).

Imagine a square circumscribed about a circle, and by using a function that sends an input at a time within the square. The point could be either within the circle also, or just be in square but not in the area covered by the circle.

By assuming the radius is one, area of the circle is πr², while square’s area is 4r². If we divide them we get π/4.

By counting the total points as TOT and the subset of those points that are within the circle also as IN, by doing the division (IN/TOT)*4 we can actually approximate with this experiment the value of pi.

/* Program to compute Pi using Monte Carlo methods */
/* You can find this code at: http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#define SEED 35791246

main(int argc, char* argv)
{
int niter=0;
double x,y;
int i,count=0; /* # of points in the 1st quadrant of unit circle */
double z;
double pi;

printf("Enter the number of iterations used to estimate pi: ");
scanf("%d",&niter);

/* initialize random numbers */
srand(SEED);
count=0;
for ( i=0; i<niter; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/niter*4;
printf("# of trials= %d , estimate of pi is %g \n",niter,pi);
}

If we give enough large value for the number of iterations we can see that we are approximating the value for pi.

--

--

Nikos Mouzakitis

Graduate of Mathematics Department in University of Aegean, Currently Computer Engineer undergrad.