Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Last active February 26, 2022 00:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thinkphp/0d56dfd5eb5f91da029a91d4c7676f12 to your computer and use it in GitHub Desktop.
Save thinkphp/0d56dfd5eb5f91da029a91d4c7676f12 to your computer and use it in GitHub Desktop.
C program to compute PI using a Monte Carlo Method.
/**
*
* Author : Adrian Statescu mergesortv@gmail.com http://adrianstatescu.com
*
* Description: C Program to compute PI using a Monte Carlo Method.
*
* MIT License
*
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define SEED time(NULL)
int main() {
srand( SEED );
int i, count, n;
double x,y,z,pi;
printf("n = ");
scanf("%d", &n);
count = 0;
for(i = 0; i < n; ++i) {
x = (double)rand() / RAND_MAX;
y = (double)rand() / RAND_MAX;
z = x * x + y * y;
if( z <= 1 ) count++;
}
pi = (double) count / n * 4;
printf("Approximate PI = %g", pi);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment