← Lesson
Distributions
Joeven
Run
Reset
Python loads on first run
import math import random random.seed(1) def bernoulli(p): return 1 if random.random() < p else 0 def uniform(a, b): return a + (b - a) * random.random() def gauss(mu=0.0, sigma=1.0): u1 = 1.0 - random.random() u2 = random.random() z = math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2) return mu + sigma * z def summarize(xs): n = len(xs) mean = sum(xs) / n var = sum((x - mean) ** 2 for x in xs) / n return mean, var ** 0.5 n = 4000 b = [bernoulli(0.3) for _ in range(n)] u = [uniform(0, 10) for _ in range(n)] g = [gauss(5, 2) for _ in range(n)] print("bernoulli mean, std", [round(x, 3) for x in summarize(b)]) print("uniform mean, std", [round(x, 3) for x in summarize(u)]) print("gauss mean, std", [round(x, 3) for x in summarize(g)]) print("P(gauss>9) ~", sum(1 for x in g if x > 9) / n)
Run to execute this in your browser. Nothing is sent to a server.