20131216

A Method to approximate Pi

This method is called Monte carlo simulation  it is a class of computer algorithm that aggregates data from a random sampling then uses laws of probability to find out some meaningful result  from the Data.

The basic idea is simple 
1-Draw a semicircle with radius r=1.00
2-And make a square of side 1 units coinciding with the circle .
3-Now randomly (uniformly ) throw some darts onto this arrangement .
4-Finally count the number of darts inside the circle(Nin) and total no of darts thrown (Ntot)
  now we know from the laws of probability that  P(Nin) = area of circular region divided by total  area of  the square , which comes to be Pi/4=Nin/Ntot

 hence Pi can be calculated by Pi = 4*(Nin/Ntot)

How do we implement this in a program ?
1 -Assume 2 axes x & y of 1000 units each .
2- Make a circle with origin as the center . and a square as shown earlier 
3- Define two variables x and y :
                  and call for a random value between 0 and 1000 for both of them separately (x,y)
4- Find the distance of this point from the origin if this distance is less than 1000 then the point is inside the circle.
5-Count the numbers of inside throws and divide by Total no of throws which was 1000 here multiply this by 4 for the value of PI π


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
    int throws,cntin=0;
    scanf("%d",&throws);
    int temp=throws;
    while(throws--)
    {
        int a=rand()%1000;
        int b=rand()%1000;
        int c=(int)(sqrt(a*a+b*b));
        if(c<1000)
        cntin++;
    }
    float ans=((4.000*cntin)/temp);
    printf("%0.02f \n",ans);

}


or download code from here


But Its more interesting like this , if you like code golfing  

1
2
3
4
5
6
7
8
#include<namit.h>
#include <stdio.h>
main()
{
    long int d = 1;
    double p = 1;
    for(;;){printf("%.20f\n",(p+=((d-1)%4)?(1.0/(d+=2)):-1.0/(d+=2))*4);}



No comments:

Post a Comment

Share your thoughts