Mar 2, 2013

[C/C++] pi calculation using Monte Carlo method

// This program calculates "pi" using Monte Carlo method.
// Think about 1/4 circle (radius=1) fitted in a square (length=1).
// The areas of 1/4 circle and square are (pi/4) and (1), respectively.
// If 100 random numbers are scattered, the quantity of scattered random numbers is proportional to the area of each shape.
// So, (pi/4) : 1 = in : total    (in=the amount of random numbers scattered inside the 1/4 circle, total=total amount of scattered random numbers)
// Now, pi can be calculated as (pi) = 4(in) / total

#include <stdio.h>
#include <stdlib.h>
#include <time.h>   // library to use "srand"

#define NUM 1000000000    // As this increases, we will get more accurate pi value.

double ran(void);

void main(void)
{
    double x,y,pi;
    int i, in=0;
    srand(time(NULL));   // change seed value for random number generation

    for(i=1; i<=NUM; i++){
        x=ran();
        y=ran();
        if(x*x+y*y <=1)
            in++;
    }
    pi=(double) 4*in/NUM;
    printf("pi = %f\n",pi);

    //return 0;
    getchar();
}


// function for generating random numbers between 0 and 1
double ran(void){
    return (double) rand()/RAND_MAX;
}

No comments:

Post a Comment