fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. srand(time(0));
  6.  
  7. int sizes[] = {1000, 10000, 100000};
  8.  
  9. for (int n : sizes) {
  10. int in = 0;
  11. for (int i = 0; i < n; i++) {
  12. double x = (double)rand() / RAND_MAX;
  13. double y = (double)rand() / RAND_MAX;
  14. if (x*x + y*y <= 1.0) in++;
  15. }
  16. double pi = 4.0 * in / n;
  17. cout << n << "\t" << in << "\t" << pi << endl;
  18. }
  19.  
  20. return 0;
  21. }
  22.  
  23. /*
  24. Q1. How does the estimate change with larger N?
  25. = As N increases, the estimate becomes more accurate and closer to π.
  26.  
  27. Q2. How close does it get to actual π?
  28. = With N=1000, error ≈ ±0.1; N=10000, error ≈ ±0.03; N=100000, error ≈ ±0.01.
  29. Larger N improves the approximation to 3.14159.
  30. */
  31.  
Success #stdin #stdout 0.01s 5328KB
stdin
Standard input is empty
stdout
1000	780	3.12
10000	7838	3.1352
100000	78608	3.14432