Skip to content

Instantly share code, notes, and snippets.

@nus
Created May 17, 2010 07:26
Show Gist options
  • Save nus/403493 to your computer and use it in GitHub Desktop.
Save nus/403493 to your computer and use it in GitHub Desktop.
/* this porgram solves PI by mote carlo method. */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 100000
double monte_carlo();
int main()
{
printf("%lf\n", monte_carlo());
return 0;
}
in_circle(double x, double y)
{
int ret = 0;
if(0.5 > sqrt(x * x + y * y)) {
ret = 1;
}
else {
ret = 0;
}
return ret;
}
double monte_carlo()
{
int i,
count_in_circle = 0,
count_in_square = 0;
double x, y,
ret_pi;
srand(time(NULL));
for(i = 0; i < MAX_NUM; i++) {
x = ((double)rand() / (double)RAND_MAX) - 0.5;
y = ((double)rand() / (double)RAND_MAX) - 0.5;
if(in_circle(x,y)) {
count_in_circle++;
}
count_in_square++;
}
ret_pi = (double)count_in_circle / MAX_NUM * 4;
return ret_pi;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment