fork download
  1. // Problem 3: Normal Distribution (Box-Muller)
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. int main() {
  7. srand(time(0));
  8. int N = 20000;
  9. double s = 0, ss = 0;
  10.  
  11. for (int i = 0; i < 10000; i++) {
  12. double u1 = (rand() + 1.0) / (RAND_MAX + 1.0);
  13. double u2 = (rand() + 1.0) / (RAND_MAX + 1.0);
  14.  
  15. double z0 = sqrt(-2 * log(u1)) * cos(2 * M_PI * u2);
  16. double z1 = sqrt(-2 * log(u1)) * sin(2 * M_PI * u2);
  17.  
  18. s += z0 + z1;
  19. ss += z0 * z0 + z1 * z1;
  20. }
  21.  
  22. double mean = s / N;
  23. double var = (ss / N) - mean * mean;
  24. double sd = sqrt(var);
  25.  
  26. cout << "Mean = " << mean << endl;
  27. cout << "Stddev = " << sd << endl;
  28.  
  29. return 0;
  30. }
  31.  
  32. /*
  33. Q1. Does your distribution resemble a bell curve?
  34. = Yes. The generated values form a bell-shaped curve (Normal Distribution).
  35.  
  36. Q2. What is the mean and stddev? Are they close to 0 and 1?
  37. = Mean is near 0, Stddev near 1. Results vary slightly since values are random,
  38. but repeated runs show they stay close to 0 and 1.
  39. */
  40.  
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Mean = -0.00238028
Stddev = 0.993051