Why they aren't really random Random Numbers Why they aren't really random
Why Random? Obvious uses Less obvious Games Simulations Cryptography – shared secret
Pseudo Random Numbers Recipe: Start with number Apply random looking math transformation eg : (num * 1009) % 100 12 8 72 48 32 88 92 28 52 68
C++ Random Need C standard library: #include <cstdlib> rand(): returns value between 0 and RAND_MAX RAND_MAX defined by library, usually ~32000
Seed Seed : starting value Same seed = same sequence 12 8 72 48 32 88 92 28 52 68 12 8 72 48 32 88 92 28 52 68 12 8 72 48 32 88 92 28 52 68
Random Seed srand(num): seeds random generator with integer value num Reproducible random : seed with constant srand(12);
Random Seed Random sequence requires random seed Sources: System clock Human input Special device Lavarand Radio noise Special hardware
Time From ctime library: #include <ctime> time(0) returns seconds since Jan 1, 1970
Random Seed srand(num): seeds random generator with integer value num Reproducible random : seed with constant srand(12); Less predictable random : seed with time srand(time(0));
C++ Random Range Use % to control range: 0 to 9: int num = rand() % 10; 0 to 29: int num = rand() % 30;
C++ Random Range Range Minimum Use + NUM for lower bound 1 to 6: int num = rand() % 6 + 1; 100 to 250: int num = rand() % 151 + 100; Range Minimum
C++ Random Other Random double Divide by max size Watch out for int division double r = static_cast<double>(rand()) / RAND_MAX;
Theoretical Notes Cycles appear when we hit repeat values Use prime numbers Use larger range of values than you really need 12 8 72 48 32 88 92 28 52 68 …
Bad Tendencies Bad recipes may Cycle easily Favor part of the number space Show patterns High always followed by low
C++ Random Numbers Aren't Good Algorithm is weak Poor distribution Limited range Serious about randomness? Use an add on library