Monte Carlo Method of finding pi using C

It works as it should. The problem is the implementation.

The C rand() function returns an integer in the range 0 to RAND_MAX. The keyword there is integer.

You then calculate the result of that integer modulo 2, which can be 0 or 1. That leaves you with 4 possible points: (0,0), (0,1), (1,0), (1,1).

Of those 4 points, only 1 lies outside of the circle of radius 1: (1,1). That is, of out of 4 possible points, 3 lie in the circle.

You should replace that code to use floating point values, not integers, so you calculate the proportion of points inside and outside of the circle.


You need to use floating-point randomization, or otherwise to use a circle with a very big radius.

So instead of

    randomx = (double)(rand() % (1+1-0) + 0);
    randomy = (double)(rand() % (1+1-0) + 0);

you use

    randomx = rand();
    randomy = rand();

and you consider if it falls inside the circle of radius RAND_MAX

   #define RMAX ((double)RAND_MAX*(double)RAND_MAX)
   equation <= RMAX;

You do the details. Read man 3 rand to see that rand() returns integer.


Your randomx and randomy variables are constrained to an integer value, because the rand() functions returns an integer.

See it live here.

As a consequence, each your two variables will be either 1 or 0, so your point will be randomly one of (0,0), (1,0), (0,1), (1,1), which has a 3:4 chance of being in the circle. Hence your result of 3.

You can look up How to generate random float number in C if you want a random number between 0 and 1.

Tags:

Pi

C

Montecarlo