CS253: Software Development with C++

Fall 2020

Random Numbers

Show Lecture.RandomNumbers as a slide show.

CS253 Random Numbers

Philosophy

“Computers can’t do anything truly random. Only a person can do that.”

Old Stuff

Traditional Method

Traditional random number generators work like this:

unsigned long n = 1;
for (int i=0; i<5; i++) {
    n = n * 16807 % 2147483647;
    cout << n << '\n';
}
16807
282475249
1622650073
984943658
1144108930

Overview

Generators

EngineDescription
default_random_engineDefault random engine
minstd_randMinimal Standard minstd_rand generator
minstd_rand0Minimal Standard minstd_rand0 generator
mt19937Mersenne Twister 19937 generator
mt19937_64Mersenne Twister 19937 generator (64 bit)
ranlux24_baseRanlux 24 base generator
ranlux48_baseRanlux 48 base generator
ranlux24Ranlux 24 generator
ranlux48Ranlux 48 generator
knuth_bKnuth-B generator
random_deviceTrue random number generator

Default Engine

Define a random-number generator, and use () to generate a number. This is not a function call, because gen is an object, not a function. It’s operator().










That sequence looks familiar …

#include <random>
#include <iostream>
using namespace std;

int main() {
    default_random_engine gen;
    for (int i=0; i<5; i++)
        cout << gen() << '\n';
}
16807
282475249
1622650073
984943658
1144108930

I won’t bother with the #includes in subsequent examples.

Mersenne Twister

mt19937_64 gen;
cout << "range is " << gen.min() << "…" << gen.max() << "\n\n";
for (int i=0; i<3; i++)
    cout << gen() << '\n';
range is 0…18446744073709551615

14514284786278117030
4620546740167642908
13109570281517897720

Ranges

Generators have varying ranges:

ranlux24 rl;
minstd_rand mr;
random_device rd;
mt19937_64 mt;

cout << "ranlux24:      " << rl.min() << "…" << rl.max() << '\n'
     << "minstd_rand:   " << mr.min() << "…" << mr.max() << '\n'
     << "random_device: " << rd.min() << "…" << rd.max() << '\n'
     << "mt19937_64:    " << mt.min() << "…" << mt.max() << '\n';
ranlux24:      0…16777215
minstd_rand:   1…2147483646
random_device: 0…4294967295
mt19937_64:    0…18446744073709551615

Hey, look! Zero is not a possible return value for minstd_rand.

Save/Restore

A generator can save & restore state to an I/O stream:

ranlux24 gen;
cout << gen() << ' ';
cout << gen() << endl;
ofstream("state") << gen;
system("wc -c state");
cout << gen() << ' ';
cout << gen() << '\n';
ifstream("state") >> gen;
cout << gen() << ' ';
cout << gen() << '\n';
15039276 16323925
209 state
14283486 7150092
14283486 7150092
endl! Isn’t that a sin? 😈 🔥

Needed to flush output before wc ran.

True randomness

random_device a, b, c;
cout << a() << '\n'
     << b() << '\n'
     << c() << '\n';
1269926981
4232381954
2269559708

Cloudflare

The hosting service Cloudflare uses a unique source of randomness.

Seeding

minstd_rand a, b, c(123);
cout << a() << ' ' << a() << '\n';
cout << b() << ' ' << b() << '\n';
cout << c() << ' ' << c() << '\n';
48271 182605794
48271 182605794
5937333 985676192

Seed with process ID

auto seed = getpid();
minstd_rand a(seed);
for (int i=0; i<5; i++)
    cout << a() << '\n';
855524613
918062313
313371331
2020192880
1645583857

Seed with time

// seconds since start of 1970
auto seed = time(nullptr);
minstd_rand a(seed);
for (int i=0; i<5; i++)
    cout << a() << '\n';
823798281
612130652
931203619
1149677392
804983458

Y2038

int biggest = 0x7fffffff;
time_t epoch = 0,
       now = time(nullptr),
       end = biggest,
       endp1 = biggest + 1;
cout << "epoch:" << setw(12) << epoch << ' ' << ctime(&epoch);
cout << "now:  " << setw(12) << now   << ' ' << ctime(&now);
cout << "end:  " << setw(12) << end   << ' ' << ctime(&end);
cout << "end+1:" << setw(12) << endp1 << ' ' << ctime(&endp1);
epoch:           0 Wed Dec 31 17:00:00 1969
now:    1729179387 Thu Oct 17 09:36:27 2024
end:    2147483647 Mon Jan 18 20:14:07 2038
end+1: -2147483648 Fri Dec 13 13:45:52 1901

I hope that nobody’s still using 32-bit signed time representations by then!

Seed with more accurate time

Nanoseconds make more possibilities:

auto seed = chrono::high_resolution_clock::now()
            .time_since_epoch().count();
cout << "Seed: " << seed << '\n';
minstd_rand a(seed);
for (int i=0; i<5; i++)
    cout << a() << '\n';
Seed: 1729179387396973085
701363558
440613263
164778385
1885477494
1379669367

Better Seeding

Seed with random_device

random_device rd;
auto seed = rd();
minstd_rand0 a(seed);
for (int i=0; i<5; i++)
    cout << a() << '\n';
1770846598
642908813
1378192034
514898896
1694131309

You can seed with random_device, if you know that it’s truly random.

Not good enough.

Caution

Distributions

uniform_int_distribution

auto seed = random_device()();  //❓❓❓
mt19937 gen(seed);
uniform_int_distribution<int> dist(1,6);
for (int y=0; y<10; y++) {
    for (int x=0; x<40; x++)
        cout << dist(gen) << ' ';
    cout << '\n';
}
6 5 1 1 3 2 6 6 5 4 3 4 2 3 1 1 4 2 5 6 1 6 3 4 6 3 6 4 4 2 3 5 1 5 4 6 5 6 1 4 
3 1 5 2 4 6 5 4 5 3 2 4 6 6 2 2 5 2 3 5 3 1 5 2 6 3 1 6 2 5 3 4 5 4 3 6 2 2 3 2 
1 6 3 2 5 2 1 5 2 5 2 5 6 5 4 1 5 1 4 6 4 1 1 1 6 2 5 1 6 4 3 2 4 6 1 3 1 2 1 5 
4 1 6 3 5 6 2 6 1 3 1 6 1 2 6 2 1 6 4 6 6 6 6 4 6 3 1 6 1 3 4 6 4 5 6 3 2 4 5 6 
4 5 4 6 6 4 1 1 2 4 6 6 6 6 5 2 4 5 3 6 6 4 4 4 2 5 4 6 5 4 5 6 3 5 5 4 5 5 1 3 
1 3 6 1 4 3 4 1 6 1 1 1 2 2 3 6 5 3 2 5 3 6 1 5 6 2 3 3 1 4 5 6 3 1 6 4 2 3 2 1 
4 6 5 6 4 3 4 5 5 4 4 4 1 3 3 4 4 4 2 5 6 1 4 1 5 1 6 5 4 6 1 2 4 4 4 3 6 3 4 6 
3 4 3 6 5 4 3 4 6 2 5 1 2 4 3 6 4 4 4 3 5 6 4 1 3 2 1 4 1 1 3 6 4 3 1 1 4 3 2 4 
3 3 3 2 1 5 1 5 5 2 6 4 3 6 4 4 1 6 1 4 3 3 6 4 1 3 5 2 2 3 6 4 6 6 3 5 1 4 6 3 
3 6 1 5 1 3 1 4 1 5 3 5 2 5 3 1 6 1 3 5 4 2 1 6 1 1 5 2 6 3 2 5 6 4 3 5 4 6 5 2 

uniform_real_distribution

auto seed = random_device()();
ranlux48 gen(seed);
uniform_real_distribution<> dist(18.0, 25.0);
for (int y=0; y<5; y++) {
    for (int x=0; x<10; x++)
        cout << fixed << setprecision(3) << dist(gen) << ' ';
    cout << '\n';
}
22.527 21.785 18.853 23.952 23.652 18.347 21.677 18.526 18.220 23.240 
19.226 19.138 23.130 19.569 19.907 20.334 24.213 20.162 19.260 18.690 
19.911 21.602 20.519 22.746 21.372 20.336 21.818 21.061 23.129 18.346 
22.552 21.195 20.791 22.064 23.465 23.866 19.286 22.409 24.095 23.149 
19.008 22.542 22.602 19.698 20.142 18.303 24.854 23.327 22.404 23.170 
OMG—what’s that <> doing there?

uniform_real_distribution’s template argument defaults to double, because … real.

Boolean Values

Yield true 42% of time:

random_device rd;
knuth_b gen(rd());
bernoulli_distribution dist(0.42);
constexpr int nrolls = 1'000'000;

int count=0;
for (int i=0; i<nrolls; i++)
    if (dist(gen))
        count++;

cout << "true: " << count*100.0/nrolls << "%\n";
true: 41.9794%

Histogram

random_device rd;
mt19937_64 gen(rd());
normal_distribution<> dist(21.5, 1.5);
map<int,int> tally;
for (int i=0; i<10000; i++)
    tally[dist(gen)]++;
for (auto p : tally)
    cout << p.first << ": " << string(p.second/100,'#') << '\n';
14: 
16: 
17: 
18: ###
19: ###########
20: #####################
21: #########################
22: #####################
23: ##########
24: ###
25: 
26: 
27: 

Passwords

random_device rd;
auto seed = rd();
ranlux24 gen(seed);
uniform_int_distribution<char> dist('!','~');
for (int y=0; y<8; y++) {
    string pw;
    for (int x=0; x<32; x++)
        pw += dist(gen);
    cout << "Password: " << pw << '\n';
}
Password: Ya#/z(NqlA.no"lohQDM%&BUc+;{8W_K
Password: $A)]<D3yX+ZOf)&cn;a!cA#Ar0+08!zO
Password: DfCg;nn3vkKiEq=bvIN13kf2GW4#,M4}
Password: ob)s;\<O(I]S>?:6""ia$w(2}@tI6&9<
Password: AV,`?)`yejtyb(0(>^~?&5r|v'!2m%o!
Password: !rY_S9*W0)ZyJdS<znVS%,--"@^MJ]@U
Password: 9W8C]sSg~w.TxVYGr})I&U>3a">xrARI
Password: WYQWi&26apA8N"+h]AU\x~W/TU2y+:ru

Even though we’re using uniform_int_distribution, which has int right there in its name, it’s uniform_int_distribution<char>, so we get characters. Think of them as 8-bit integers that display differently.