fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5.  
  6. #define NUM_POINTS 1000000
  7. #define TRUE_AREA (M_PI - 3 * sqrt(3) + 3) / 3
  8. #define NUM_STEPS 12
  9.  
  10. int is_inside(double x, double y) {
  11. double r = 1.0;
  12. if ((x - 0) * (x - 0) + (y - 1) * (y - 1) <= r * r &&
  13. (x - 1) * (x - 1) + (y - 0) * (y - 0) <= r * r &&
  14. (x - 0) * (x - 0) + (y - 0) * (y - 0) <= r * r &&
  15. (x - 1) * (x - 1) + (y - 1) * (y - 1) <= r * r) {
  16. return 1;
  17. }
  18. return 0;
  19. }
  20.  
  21. int main() {
  22. int i, inside_count = 0;
  23. double x, y;
  24. double estimated_area;
  25. double error;
  26. int step_size = NUM_POINTS / NUM_STEPS;
  27.  
  28. srand(time(NULL));
  29.  
  30. printf("乱数の個数, 誤差\n");
  31.  
  32. for (i = 1; i <= NUM_POINTS; i++) {
  33. x = (double)rand() / RAND_MAX;
  34. y = (double)rand() / RAND_MAX;
  35.  
  36. if (is_inside(x, y)) {
  37. inside_count++;
  38. }
  39.  
  40. if (i % step_size == 0) {
  41. estimated_area = 4.0 * (double)inside_count / i;
  42. error = fabs(estimated_area - TRUE_AREA);
  43.  
  44. printf("%d,%f\n", i, error);
  45. }
  46. }
  47.  
  48. printf("計算が完了しました。\n");
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.05s 5232KB
stdin
Standard input is empty
stdout
乱数の個数, 誤差
83333,0.945194
166666,0.942674
249999,0.942570
333332,0.939170
416665,0.938993
499998,0.941210
583331,0.942115
666664,0.943004
749997,0.943968
833330,0.945170
916663,0.945369
999996,0.945498
計算が完了しました。