Lecture 18 – Data 100, Summer 2025¶

Data 100, Summer 2025

Acknowledgments Page

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]:
0    1
1    0
1    0
1    0
0    1
1    0
1    0
1    0
0    1
0    1
Name: x, dtype: int64
In [4]:
N = 10000

np.random.rand(N,2) < p
Out[4]:
array([[ True,  True],
       [False,  True],
       [ True, False],
       ...,
       [ True,  True],
       [ True, False],
       [ True,  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 10
4 20
... ...
9995 0
9996 0
9997 20
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 13
1 10 5
2 10 12
3 10 13
4 20 11
... ... ...
9995 0 8
9996 0 13
9997 20 11
9998 20 8
9999 10 9

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 13 20
1 10 5 20
2 10 12 0
3 10 13 0
4 20 11 20
... ... ... ...
9995 0 8 20
9996 0 13 20
9997 20 11 20
9998 20 8 0
9999 10 9 0

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 9.930000 10.011200 9.966000
Simulated Var 50.480148 5.006375 100.008845
Siumulated SD 7.104938 2.237493 10.000442
In [ ]: