In [1]:
import pandas as pd
import numpy as np
import plotly.express as px
Which would you pick?¶
- $\large Y_A = 10 X_1 + 10 X_2 $
- $\large Y_B = \sum\limits_{i=1}^{20} X_i$
- $\large Y_C = 20 X_1$
First let's construct the probability distribution for a single coin. This will let us flip 20 IID coins later.
In [2]:
# First construct probability distribution for a single fair coin
p = 0.5
coin_df = pd.DataFrame({"x": [1, 0], # [Heads, Tails]
"P(X = x)": [p, 1 - p]})
coin_df
Out[2]:
x | P(X = x) | |
---|---|---|
0 | 1 | 0.5 |
1 | 0 | 0.5 |
Choice A:¶
$\large Y_A = 10 X_1 + 10 X_2 $
A couple ways to sample:
In [3]:
coin_df.sample(10, weights="P(X = x)", replace=True)["x"]
Out[3]:
1 0 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 Name: x, dtype: int64
In [4]:
N = 10000
np.random.rand(N,2) < p
Out[4]:
array([[False, False], [ True, True], [ True, False], ..., [ True, True], [ True, True], [False, True]])
In [5]:
sim_flips = pd.DataFrame(
{"Choice A": np.sum((np.random.rand(N, 2) < p) * 10, axis=1)})
sim_flips
Out[5]:
Choice A | |
---|---|
0 | 10 |
1 | 10 |
2 | 10 |
3 | 20 |
4 | 10 |
... | ... |
9995 | 0 |
9996 | 10 |
9997 | 10 |
9998 | 20 |
9999 | 10 |
10000 rows × 1 columns
Choice B:¶
$\large Y_B = \sum\limits_{i=1}^{20} X_i$
In [6]:
sim_flips["Choice B"] = np.sum((np.random.rand(N,20) < p), axis=1)
sim_flips
Out[6]:
Choice A | Choice B | |
---|---|---|
0 | 10 | 11 |
1 | 10 | 9 |
2 | 10 | 7 |
3 | 20 | 13 |
4 | 10 | 10 |
... | ... | ... |
9995 | 0 | 17 |
9996 | 10 | 11 |
9997 | 10 | 9 |
9998 | 20 | 11 |
9999 | 10 | 14 |
10000 rows × 2 columns
Choice C:¶
$\large Y_C = 20 X_1$
In [7]:
sim_flips["Choice C"] = 20 * (np.random.rand(N,1) < p)
sim_flips
Out[7]:
Choice A | Choice B | Choice C | |
---|---|---|---|
0 | 10 | 11 | 20 |
1 | 10 | 9 | 0 |
2 | 10 | 7 | 20 |
3 | 20 | 13 | 20 |
4 | 10 | 10 | 20 |
... | ... | ... | ... |
9995 | 0 | 17 | 20 |
9996 | 10 | 11 | 20 |
9997 | 10 | 9 | 0 |
9998 | 20 | 11 | 0 |
9999 | 10 | 14 | 20 |
10000 rows × 3 columns
If you're curious as to what these distributions look like, I've simulated some populations:
In [8]:
px.histogram(sim_flips.melt(), x="value", facet_row="variable",
barmode="overlay", histnorm="probability",
title="Empirical Distributions",
width=600, height=600)
In [9]:
pd.DataFrame([
sim_flips.mean().rename("Simulated Mean"),
sim_flips.var().rename("Simulated Var"),
np.sqrt(sim_flips.var()).rename("Siumulated SD")
])
Out[9]:
Choice A | Choice B | Choice C | |
---|---|---|---|
Simulated Mean | 10.017000 | 10.042000 | 10.046000 |
Simulated Var | 50.514762 | 4.973533 | 100.007885 |
Siumulated SD | 7.107374 | 2.230142 | 10.000394 |
In [ ]: