An interesting way of calculating pi is to use a technique k

An interesting way of calculating (pi) is to use a technique known as Monte Carlo, which involves randomization. This technique works as follows: Suppose you have a circle inscribed within a square, as shown below. Assume that the radius of this circle is 1. First, generate a series of random points as simple (x, y) coordinates. These points must fall within the Cartesian coordinates that bound the square. Of the total number of random points that are generated, some will occur within the circle.

Next, estimate ? (pi) by performing the following calculation:

? = 4 x (number of points in circle) / (total number of points)

Write a multithreaded version of this algorithm in C that uses pthreads to create one or more separate threads to generate a number of random points. The thread will count the number of points that occur within the circle and store that result in a global variable. When this thread has exited, the parent thread will calculate and output the estimated value of ? (pi). It is worth experimenting with the number of random points generated. As a general rule, the greater the number of points, the closer the approximation to ? (pi).

(0,0)

Solution

#include <stdlib.h> // For random(), RAND_MAX
#include<stdio.h>
#include<math.h>
#define total 1200

int checkvalue(int r, float x, float y)
{
float dis,d;
int count = 0;
//Considering center as (0,0) as per the example
dis = x*x + y*y;
d = r*r;
if(dis == d)
{
printf(\"\ Point is on the circle\ \");
return 1;
}
else
{
if(dis>d)
{
printf(\"Point is outside the circle\ \");
return 0;
}
else
{
printf(\"Point is inside the circle\ \");
return 1;
}

}

return 0;
}

void main()
{   
int max = 1, min = -1,r,p,count = 0;
float x[total], y[total],pi;
//Radius given is 1
r = 1;
for(int i = 0; i< total; i++)
{
x[i] = (2 * ((float)rand()/RAND_MAX) - 1) ;
}
for(int i = 0; i< total; i++)
{
y[i] = (2 * ((float)rand()/RAND_MAX) - 1) ;
}
printf(\"Point are :\");
for(int i = 0; i< total; i++)
{
printf(\"(%f,%f)\ \", x[i],y[i]);
}
for(int i = 0; i< total; i++)
{
p = checkvalue(r,x[i],y[i]);
if (p == 1)
{
printf(\"Point : (%f,%f)\ \",x[i],y[i]);
count = count + 1;
}
}
printf(\"count = %d\", count);
pi = (float) 4 * (count / (total * 1.0));
printf(\"\ The value of pi : %f \", pi);
}
  

An interesting way of calculating (pi) is to use a technique known as Monte Carlo, which involves randomization. This technique works as follows: Suppose you ha

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site