Advertisement
Guest User

C++ Random generator demo

a guest
Oct 14th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <cstdio>
  2. #include <ctime>
  3. #include <random>
  4.  
  5. static std::random_device rd;
  6. std::mt19937 gen_eng(rd.entropy() ? rd() : (unsigned long)(std::time(nullptr)));
  7. //Or just "std::mt19937 generator(SOME_CONST);" for repeated sequence. Try it!
  8.  
  9. double genAlpha() {
  10.   static std::uniform_real_distribution<double> unif_real_01(0.0, 1.0);
  11.   return unif_real_01(gen_eng);
  12. }
  13.  
  14. int main() {
  15.   printf("%lf\n", genAlpha());
  16.   printf("%lf\n", genAlpha());
  17.   printf("%lf\n", genAlpha());
  18.   printf("%lf\n", genAlpha());
  19.  
  20.   printf("\nMmm... Dice throwing:\n");
  21.   int dice_result = 6 * genAlpha() + 1;
  22.   printf("%d\n", dice_result);
  23.  
  24.   printf("\nADVANCED\nWe can get another distributions:\n");
  25.   printf("1) Dice (\"right\" way):\n");
  26.  
  27.   std::uniform_int_distribution<int> unif_int_16(1, 6);
  28.  
  29.   printf("%d\n", unif_int_16(gen_eng));
  30.   printf("%d\n", unif_int_16(gen_eng) + unif_int_16(gen_eng) + unif_int_16(gen_eng));
  31.   printf("2) Normal:\n");
  32.  
  33.   static std::normal_distribution<double> std_norm_dist(0, 1);
  34.  
  35.   printf("%lf\n", std_norm_dist(gen_eng));
  36.   printf("%lf\n", std_norm_dist(gen_eng));
  37.   printf("%lf\n", std_norm_dist(gen_eng));
  38.   printf("%lf\n", std_norm_dist(gen_eng));
  39.  
  40.   return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement