Last active
February 26, 2022 00:59
-
-
Save thinkphp/0d56dfd5eb5f91da029a91d4c7676f12 to your computer and use it in GitHub Desktop.
C program to compute PI using a Monte Carlo Method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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