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 sum = 0, sumSq = 0;
  10. int pairs = N / 2;
  11.  
  12. cout << "Generating " << N << " normal random values...\n";
  13.  
  14. for (int i = 0; i < pairs; i++) {
  15. double u1 = (rand() + 1.0) / (RAND_MAX + 1.0);
  16. double u2 = (rand() + 1.0) / (RAND_MAX + 1.0);
  17.  
  18. double z0 = sqrt(-2.0 * log(u1)) * cos(2 * M_PI * u2);
  19. double z1 = sqrt(-2.0 * log(u1)) * sin(2 * M_PI * u2);
  20.  
  21. sum += z0 + z1;
  22. sumSq += z0 * z0 + z1 * z1;
  23. }
  24.  
  25. double mean = sum / N;
  26. double variance = (sumSq / N) - mean * mean;
  27. double stddev = sqrt(variance);
  28.  
  29. cout << "\nStatistics:\n";
  30. cout << "Mean : " << mean << endl;
  31. cout << "StdDev : " << stddev << endl;
  32.  
  33. return 0;
  34. }
  35.  
  36. /*
  37. Q1. Does your distribution resemble a bell curve?
  38. = Yes. The generated numbers follow a bell-shaped (Normal) distribution.
  39.  
  40. Q2. What is the mean and stddev? Are they close to 0 and 1?
  41. = Mean is approximately 0 and StdDev approximately 1. Randomness causes slight variations,
  42.   but repeated runs confirm they stay near 0 and 1.
  43. */
  44.  
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Generating 20000 normal random values...

Statistics:
Mean       : 0.00203272
StdDev     : 1.00312