fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. #define M_PI 3.14159265
  6.  
  7. double true_area() {
  8. return 9.0;
  9. }
  10.  
  11. int main() {
  12. double x, y, s, r = 1.0;
  13. int n, m;
  14. double area_true = true_area();
  15.  
  16. for (n = 10; n <= 100000; n *= 10) {
  17. s = 0.0;
  18.  
  19. for (m = 0; m < n; m++) {
  20. x = (double)rand() / RAND_MAX * 2.0 - 1.0;
  21. y = (double)rand() / RAND_MAX * 2.0 - 1.0;
  22.  
  23. if ((x * x + y * y <= r * r) &&
  24. (x - 1.0) * (x - 1.0) + y * y <= r * r &&
  25. (x * x + (y - 1.0) * (y - 1.0)) <= r * r &&
  26. ((x - 1.0) * (x - 1.0) + (y - 1.0) * (y - 1.0)) <= r * r) {
  27. s += 1.0;
  28. }
  29. }
  30.  
  31. double area_estimated = (s / n) * 4.0;
  32. double error = fabs(area_estimated - area_true);
  33.  
  34. printf("n = %d, 誤差 = %f\n", n, error);
  35. }
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
n = 10, 誤差 = 8.200000
n = 100, 誤差 = 8.760000
n = 1000, 誤差 = 8.624000
n = 10000, 誤差 = 8.720000
n = 100000, 誤差 = 8.683800