fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <math.h>
  5.  
  6. int main() {
  7. int N_values[] = {1000, 10000, 100000};
  8. int num_cases = sizeof(N_values) / sizeof(N_values[0]);
  9. int i, N, count;
  10. double x, y, pi_estimate;
  11.  
  12. // Seed the random number generator
  13. srand(time(NULL));
  14.  
  15. printf("Monte Carlo Estimation of π\n");
  16. printf("-------------------------------------\n");
  17.  
  18. for (i = 0; i < num_cases; i++) {
  19. N = N_values[i];
  20. count = 0;
  21.  
  22. for (int j = 0; j < N; j++) {
  23. x = (double)rand() / RAND_MAX; // x in [0, 1)
  24. y = (double)rand() / RAND_MAX; // y in [0, 1)
  25. if ((x * x + y * y) <= 1.0) {
  26. count++;
  27. }
  28. }
  29.  
  30. pi_estimate = 4.0 * count / N;
  31. printf("N = %-7d => Estimated π = %.6f\n", N, pi_estimate);
  32. }
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Monte Carlo Estimation of π
-------------------------------------
N = 1000    => Estimated π = 3.152000
N = 10000   => Estimated π = 3.158800
N = 100000  => Estimated π = 3.139360