For a tiny population you can list every possible sample and check the central limit theorem's numbers exactly.
What to build
A program that builds the whole sampling distribution of the mean.
Requirements
- List every ordered sample of size n drawn with replacement. Print
samples K,mean of sample means A,population mean M,sd of sample means Sandsigma over root n R, the numbers to 3 decimal places.
Input
Line 1: the population's values. Line 2: n.
Output
Five lines.
Constraints
1 to 6 values; 1 ≤ n ≤ 4.
Example
Input:
1 2 3
2
Output:
samples 9
mean of sample means 2.000
population mean 2.000
sd of sample means 0.577
sigma over root n 0.577
Why it works
Every sample is equally likely, so averaging over all of them gives the exact sampling distribution, whose mean equals the population mean and whose spread equals σ ÷ √n.
Examples
Example 1 · Input
1 2 3 2
Expected output
samples 9 mean of sample means 2.000 population mean 2.000 sd of sample means 0.577 sigma over root n 0.577
Example 2 · Input
0 10 1
Expected output
samples 2 mean of sample means 5.000 population mean 5.000 sd of sample means 5.000 sigma over root n 5.000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
itertools.product(values, repeat=n) lists every ordered sample with replacement.
Hint 2
Use the population standard deviation (divide by the count) for both the sample means and the population.
Solution
Show one correct solution (try it yourself first)
from itertools import product
values = list(map(float, input().split()))
n = int(input())
def sd(xs):
m = sum(xs) / len(xs)
return (sum((x - m) ** 2 for x in xs) / len(xs)) ** 0.5
means = [sum(s) / n for s in product(values, repeat=n)]
print("samples", len(means))
print(f"mean of sample means {sum(means) / len(means):.3f}")
print(f"population mean {sum(values) / len(values):.3f}")
print(f"sd of sample means {sd(means):.3f}")
print(f"sigma over root n {sd(values) / n ** 0.5:.3f}")