import numpy as npOur goals are to
- practice Python
- practice general expectations, namely
\[ \mathbb{E}[g(X)] = \sum_{x \in S} g(x) \cdot f(x) \]
All of this will only work for a specific class of distributions, namely ones which have a finite sample space. This won’t work for more general distributions, which we will get to in class soon.
def general_expectation(s, f, g, **kwargs):
return np.sum(g(s, **kwargs) * f(s, **kwargs))def uniform_density(x, a = 1, b = 6, **kwargs):
xa = x < a
xb = x > b
idx = xa | xb
d = np.zeros_like(x)
d[~idx] = 1 / (b - a + 1)
return ddef EX(x, f, **kwargs):
def m(x, **kwargs):
return x
return general_expectation(x, f, m, **kwargs)a = -13
b = 6873
SU = np.arange(a, b + 1, dtype = np.float64)
EX(SU, uniform_density, a = a, b = b)3430.0
def VX(x, f, **kwargs):
def v(x, **kwargs):
return (x - EX(x, f, **kwargs)) ** 2
return general_expectation(x, f, v, **kwargs)VX(SU, uniform_density, a = a, b = b)3952564.0
((b - a + 1) ** 2 - 1) / 123952564.0
def PX(x, f, **kwargs):
def px(x, **kwargs):
return np.isin(x, kwargs["A"]) # x == kwargs["A"]
return general_expectation(x, f, px, **kwargs)PX(SU, uniform_density, a = a, b = b, A = np.array([1., 2, 3]))0.00043560331058516046