-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathst-petersburg-paradox.cpp
53 lines (40 loc) · 1.37 KB
/
st-petersburg-paradox.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <random>
#include <cmath>
#include <map>
using namespace std;
const unsigned long kSimulations = 10000000;
int main() {
random_device rd;
mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
binomial_distribution<> binomial(1, 0.5);
unsigned long long total_win = 0;
map<long, long> win_list;
for (int i = 1; i <= kSimulations; i++) {
int nth_flip = 0;
short heads = 0;
do {
heads = binomial(gen);
++nth_flip;
if (heads == 1) {
total_win += pow(2, nth_flip);
} else if (heads == 0) {
long last_flip_win = pow(2, nth_flip-1);
if (nth_flip-1 == 0) last_flip_win = 0;
// append win to win_list
if (win_list.count(last_flip_win) > 0) {
win_list[last_flip_win] += 1;
} else {
win_list[last_flip_win] = 1;
}
}
}
while (heads == 1);
}
double expected_win = (double)total_win / (double)kSimulations;
cout << "Expected Winnings: " << expected_win << endl << endl;
for (auto &win: win_list) {
cout << "Won " << win.first << "$ " << win.second << " times" << endl;
}
return 0;
}