Home      Affiliated Colleges      Course content      First Sem     Second Sem     Third Sem     Fourth Sem     Fifth Sem     Sixth Sem     Seventh Sem     Eighth Sem     Lab report 4th sem     Contact    

Thursday, January 27, 2011

Simulation and Modeling: Simulation of Monte Carlo for determination of PI Using C:

Title:
Monte Carlo Simulation: Determination of π.

Objective:
To find the value of  π for different value of N using Monte Carlo simulation and find the difference between actual value of  and calculated value of π.

Theory:
To calculate value of pi we use a circle.
We know,
Area of circle= π r2
And, the eqn of circle with centre (0,0) is x2+y2=r2

Now, assuming that we draw a circle with radius r in a square board with side 2r and we hit dart on it. Then from Monte Carlo simulation method:

No. of dart hitting on or inside circle =     Area of Circle.
No. of dart hitting n side square              Area of Square 

 n   =     π r2                                      
N         4r2
  π  =    4n
            N

Now, equation of circle,
            x2+y2=r2
Assuming it as a function,
            f(x,y)=x2+y2-r2
if r=1
            f(x,y)=x2+y2-1
If(x,y) lies inside or on the circle then f(x,y)<=0
If(x,y) lies inside or on the square then f(x,y)>0


Source Code:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define pie 3.1415167

void main()
{
            clrscr();
            randomize();
            int i,N,n=0;
            double x,y,fxy,pi,err;

            printf("\n Enter the no. N:");
            scanf("%d",&N);

            for(i=0;i<N;i++)
            {

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

                        if(fxy<=0.0)
                                    n++;
            }

            pi=(4*n)/(float)N;
            err=(pie-pi)/pie*100;


            printf("\nThe value of N: %d",N);
            printf(" \n The value of n: %d",n);
            printf("\n %f",pi);

            printf("\n Error is: %lf",err);
            getch();

}

Output:


In this way, the value of π is determined using Monte Carlo Simulation Method.

No comments:

Post a Comment

^ Scroll to Top Related Posts with Thumbnails ^ Go to Top