Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:14

0001 // name=rng ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
0002 
0003 // https://stackoverflow.com/questions/31417957/encapsulated-random-number-generator-in-c-11-using-boost
0004 
0005 #include <iostream>
0006 #include <iomanip>
0007 #include <random>
0008 
0009 template <typename T>
0010 struct RNG
0011 {
0012     std::mt19937_64 engine ;
0013     std::uniform_real_distribution<T>  dist ; 
0014 
0015     RNG(unsigned seed_=0u) : dist(0, 1) { engine.seed(seed_); }
0016     T operator()(){ return dist(engine) ; }
0017 };
0018 
0019 
0020 template <typename T>
0021 void test_rng( const std::function<T()>& fn )
0022 {
0023     T a ; 
0024     T b ; 
0025     bool done ; 
0026     unsigned count = 0 ; 
0027 
0028     do {
0029         a = fn() ; 
0030         b = fn() ; 
0031         std::cout 
0032             << " count " << std::setw(10) <<  count 
0033             << " a " << std::fixed << std::setw(10) << std::setprecision(4) <<  a 
0034             << " b " << std::fixed << std::setw(10) << std::setprecision(4) <<  b 
0035             << std::endl
0036             ; 
0037 
0038         done = a > 0.99 && b > 0.99 ; 
0039         count += 1 ;   
0040 
0041     } while( done == false ) ; 
0042 
0043 
0044     std::cout 
0045         << " result " 
0046         << " count " << count 
0047         << " a " << a 
0048         << " b " << b 
0049         << std::endl
0050         ; 
0051 }
0052 
0053 
0054 int main()
0055 {
0056     unsigned seed = 1u ; 
0057     //RNG<double> rng0(seed) ; 
0058     //test_rng<double>(rng0); 
0059 
0060     RNG<float> rng1(seed) ; 
0061     test_rng<float>(rng1); 
0062 
0063     return 0;
0064 }
0065 
0066