import numpy as np
The formula for a mean \(\frac{1}{N} \sum_{n=1}^N x_n\) naturally relates to the definition of an expectation
\[\mathbb{E}[X] = \sum_{x \in S} x \cdot f(x)\]
you just have to squint.
# X ~ Uniform(1, 6)
= np.arange(6) + 1
x = 1/6 fx
sum(x * fx) # E[X] np.
3.5
= np.random.default_rng()
rng = rng.integers(1, 7, size = 1000000) x
np.mean(x)
3.500221
== 4) # proportion of x values equal to 4, estimates 1/6 np.mean(x
0.166322
The formula for the mean estimates the density function at each value of \(x\), e.g. \(x = 4\). As such, here are various (numerically inefficient) ways to think about the formula for a mean.
= 0
s for i in range(1, 7): # Python for-loop
+= np.mean(x == i) * i # s = s + np.mean(x == i) * i
s s
3.500221
sum([np.mean(x == i) * i for i in range(1, 7)]) # list comprehension np.
3.500221
sum(np.mean(x == i) * i for i in range(1, 7)) # generator
3.500221
= np.zeros(6)
p = np.size(x)
N for xi in x:
-1] += 1 / N
p[xisum(np.arange(1, 7) * p)
np.# we should be able to re-use variables from above to simplify this, but I used x for both
# the random numbers and the values in the support of the Uniform(1, 6) distribution.
# For shame, Edward.
3.500221000003066