fork download
  1. // Problem 2: Monte Carlo Estimation of π
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. int main() {
  7. srand(time(0));
  8.  
  9. int Nvals[] = {1000, 10000, 100000};
  10. for (int i = 0; i < 3; i++) {
  11. int N = Nvals[i], in = 0;
  12. for (int j = 0; j < N; j++) {
  13. double x = (double)rand() / RAND_MAX;
  14. double y = (double)rand() / RAND_MAX;
  15. if (x * x + y * y <= 1.0) in++;
  16. }
  17. double pi = 4.0 * in / N;
  18. cout << "N=" << N << " -> pi≈" << pi << endl;
  19. }
  20. return 0;
  21. }
  22.  
  23. /*
  24. Q1. How does the estimate change with larger N?
  25. = With larger N, the estimate becomes more accurate and converges to π.
  26.  
  27. Q2. How close does it get to actual π?
  28. = For N=1000, error is about ±0.1. For N=10000, error ≈ ±0.03.
  29. For N=100000, error ≈ ±0.01. Larger N gives closer results to 3.14159.
  30. */
  31.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
N=1000 -> pi≈3.128
N=10000 -> pi≈3.1268
N=100000 -> pi≈3.14272