// // // // // Lab. Calcolo II - Esempio di codice // // // // // // // // Example code: gaussian-distributed random numbers // (20060911 francesco.prelz@mi.infn.it) #include <iostream> #include <iomanip> #include <random> #include <cmath> int main (int argc, char *argv[]) { const int n_repeats = 10; double x,y; double sigma = 1; double max = 10; double min = -10; double sqr2pi = std::sqrt(2*M_PI); bool found; // Pick random coordinates inside a (max-min)x(1/(sqr(2PI)*sigma)) square std::random_device rndgen; std::uniform_real_distribution<double> rndstx(min, max); std::uniform_real_distribution<double> rndsty(0,1/sqr2pi/sigma); for (int i=1; i<=n_repeats; i++) { found = false; while (!found) { x = rndstx(rndgen); y = rndsty(rndgen); if (y < (1/(sigma*sqr2pi)) * exp(-x*x/(2*sigma*sigma))) { found = true; } } std::cout << "Number # " << std::setw(2) << i << " is " << x << std::endl; } // For reference: same exercise using c++11 'random' library: std::normal_distribution<double> gaussdist(0, sigma); for (int i=1; i<=n_repeats; i++) { x = gaussdist(rndgen); std::cout << "STD Number # " << std::setw(2) << i << " is " << x << std::endl; } return 0; }