fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. #define M_PI 3.14159265
  6.  
  7. int isInsideCircle(double x, double y, double centerX, double centerY) {
  8. return (pow(x - centerX, 2) + pow(y - centerY, 2)) < 1.0;
  9. }
  10.  
  11. int main() {
  12. double x, y;
  13. int count, n;
  14. double areaEstimate, intersectionArea;
  15. intersectionArea = 0.0;
  16.  
  17. printf("n\tError\n");
  18.  
  19. for (n = 10; n <= 100000; n *= 5) {
  20. count = 0;
  21. areaEstimate = 0.0;
  22.  
  23. for (int m = 0; m < n; m++) {
  24. x = (double)rand() / RAND_MAX;
  25. y = (double)rand() / RAND_MAX;
  26.  
  27. if (isInsideCircle(x, y, 0, 0) &&
  28. isInsideCircle(x, y, 1, 0) &&
  29. isInsideCircle(x, y, 0, 1) &&
  30. isInsideCircle(x, y, 1, 1)) {
  31. areaEstimate += 1.0;
  32. }
  33. count++;
  34. }
  35.  
  36. areaEstimate /= count;
  37. double theoreticalArea = M_PI - 4;
  38. printf("%d\t%f\n", n, fabs(areaEstimate - theoreticalArea));
  39. }
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
n	Error
10	1.258407
50	1.158407
250	1.214407
1250	1.165607
6250	1.185607
31250	1.171591