fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #define M_PI 3.14159265
  5.  
  6. int main() {
  7. double a, b, s, q1, q2, q3, q4, r, actual_area;
  8. int count, m, n;
  9.  
  10. // Set the actual area (based on theoretical calculation for verification)
  11. actual_area = M_PI - 2; // Exact area of the region (adjust this according to problem specifics)
  12.  
  13. r = 1.0; // Radius of the unit circle
  14. count = 0;
  15.  
  16. for(n = 10; n < 100000; n = n * 5) {
  17. count = 0;
  18. s = 0.0;
  19. for(m = 0; m < n; m++) {
  20. a = (double)rand() / RAND_MAX; // Random x-coordinate
  21. b = (double)rand() / RAND_MAX; // Random y-coordinate
  22.  
  23. // Check if point (a,b) is within all four unit circles centered at (0,0), (0,1), (1,0), (1,1)
  24. q1 = (a - 0.0) * (a - 0.0) + (b - 0.0) * (b - 0.0); // Distance from center (0,0)
  25. q2 = (a - 1.0) * (a - 1.0) + (b - 0.0) * (b - 0.0); // Distance from center (1,0)
  26. q3 = (a - 0.0) * (a - 0.0) + (b - 1.0) * (b - 1.0); // Distance from center (0,1)
  27. q4 = (a - 1.0) * (a - 1.0) + (b - 1.0) * (b - 1.0); // Distance from center (1,1)
  28.  
  29. // Count if the point lies inside all four circles
  30. if(q1 < r && q2 < r && q3 < r && q4 < r) {
  31. s += 1.0;
  32. }
  33. count++;
  34. }
  35.  
  36. s /= count; // Proportion of points within the common region
  37. double estimated_area = s * 1.0; // Bounding box area is 1.0 (since we're in a 1x1 square)
  38.  
  39. // Print the number of random points and the error compared to the theoretical area
  40. printf("Points: %d\tEstimated Area: %f\tError: %f\n", n, estimated_area, fabs(estimated_area - actual_area));
  41. }
  42.  
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Points: 10	Estimated Area: 0.400000	Error: 0.741593
Points: 50	Estimated Area: 0.300000	Error: 0.841593
Points: 250	Estimated Area: 0.356000	Error: 0.785593
Points: 1250	Estimated Area: 0.307200	Error: 0.834393
Points: 6250	Estimated Area: 0.327200	Error: 0.814393
Points: 31250	Estimated Area: 0.313184	Error: 0.828409