Skip to content

Instantly share code, notes, and snippets.

@davipatti
Created August 14, 2024 13:27
Show Gist options
  • Save davipatti/4e4e4cba9e9838341512f400db9d4453 to your computer and use it in GitHub Desktop.
Save davipatti/4e4e4cba9e9838341512f400db9d4453 to your computer and use it in GitHub Desktop.
[mean set containment] What is the probability a set of size N contains its mean?
#!/usr/bin/env python3
import random
import matplotlib.pyplot as plt
numbers = tuple(range(100))
def trial(N: int) -> bool:
S = random.choices(numbers, k=N)
return sum(S) // N in S
def trials(N: int, repeats: int) -> float:
return sum(trial(N) for _ in range(repeats)) / repeats
N = tuple(range(1, 500, 5))
with plt.xkcd():
plt.scatter(
N, [trials(N=n, repeats=500) for n in N], c="black", clip_on=False, zorder=20
)
plt.ylim(0, 1)
plt.xlabel("N")
plt.ylabel("Probability")
plt.title(
"Probability set of N random numbers contains its mean\n"
"(numbers drawn at random from 0-99, 500 repeats per N)",
pad=15,
)
plt.savefig("set-mean-containment.png", bbox_inches="tight", dpi=300)
@davipatti
Copy link
Author

set-mean-containment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment