Imagine a square in the plane from coordinates (-1, -1) to (1,1), and also imagine a circle having radius 1 and origin in (0,0).

Generate a random number x in interval (-1, 1), and a random number y also in (-1, 1). What is the probability that (x, y) is inside the circle?

I hope you agree that the probability is the area of the circle over the area of the square: .

This means that if we randomly generate many points inside the square the number of the points inside the circle will be multiplied by the total number of points generated.

Based on this idea, following C code will compute an approximation of :

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

int main()

{

srand(0);

long maxIterarions = LONG_MAX/200;

double inCircle = 0.0;

for (long i = 0; i < maxIterarions; i++)

{

//generate x in interval [-1, 1]

double x = -1 + 2 * ( ( (double)rand() ) / RAND_MAX );

//generate y in interval [-1, 1]

double y = -1 + 2 * ( ( (double)rand() ) / RAND_MAX );

//count if point (x,y) is inside the unit circle

**if ( x*x + y*y <= 1 )**

**{**

**inCircle++;**

**}**

}

printf(“pi=%lf\n”,

**(4*inCircle)/maxIterarion**s); getch();

return 0;

}

Advertisements