fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. srand(time(0));
  6.  
  7. int nVals[] = {1000, 10000, 100000};
  8. for (int i = 0; i < 3; i++) {
  9. int n = nVals[i], cnt = 0;
  10. for (int j = 0; j < n; j++) {
  11. double x = (double)rand() / RAND_MAX;
  12. double y = (double)rand() / RAND_MAX;
  13. if (x*x + y*y <= 1.0) cnt++;
  14. }
  15. double pi = 4.0 * cnt / n;
  16. cout << "N=" << n << " -> pi≈" << pi << endl;
  17. }
  18. return 0;
  19. }
  20.  
  21. /*
  22. Q1. How does the estimate change with larger N?
  23. = Increasing N improves the estimate and makes it closer to π.
  24.  
  25. Q2. How close does it get to actual π?
  26. = For N=1000, error is ~±0.1; N=10000, error ~±0.03; N=100000, error ~±0.01.
  27. Higher N gives values nearer to 3.14159.
  28. */
  29.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
N=1000 -> pi≈3.18
N=10000 -> pi≈3.1404
N=100000 -> pi≈3.14252