fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. /*
  5. Q1. What is the purpose of Box-Muller Transform?
  6. Ans: It generates normally distributed random numbers from uniform random numbers.
  7.  
  8. Q2. What are the expected mean and standard deviation?
  9. Ans: For a standard normal distribution: Mean ≈ 0, StdDev ≈ 1.
  10.  
  11. Q3. What do you observe from generated values?
  12. Ans: With N=10000, the sample mean is very close to 0 and sample stddev close to 1, confirming normal distribution.
  13. */
  14.  
  15. int main() {
  16. srand(time(0));
  17. int N = 10000;
  18. vector<double> values;
  19.  
  20. for (int i = 0; i < N/2; i++) {
  21. double u1 = (double)rand() / RAND_MAX;
  22. double u2 = (double)rand() / RAND_MAX;
  23. double R = sqrt(-2 * log(u1));
  24. double z1 = R * cos(2*M_PI*u2);
  25. double z2 = R * sin(2*M_PI*u2);
  26. values.push_back(z1);
  27. values.push_back(z2);
  28. }
  29.  
  30. double mean = accumulate(values.begin(), values.end(), 0.0) / values.size();
  31. double sq_sum = 0;
  32. for (double v : values) sq_sum += (v - mean) * (v - mean);
  33. double stddev = sqrt(sq_sum / values.size());
  34.  
  35. cout << "Box-Muller Normal Distribution:\n";
  36. cout << "Generated " << N << " values.\n";
  37. cout << "Mean ≈ " << mean << ", StdDev ≈ " << stddev << endl;
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Box-Muller Normal Distribution:
Generated 10000 values.
Mean ≈ 0.00943434, StdDev ≈ 1.01028