import numpy as np
import matplotlib.pyplot as plt

# a
p = 0.3
n_werte = [10, 50, 200, 1000]
fig, axes = plt.subplots(1, 4, figsize=(14, 3))
for ax, n in zip(axes, n_werte):
    stichprobe = np.random.binomial(n, p, size=10000)
    ax.hist(stichprobe, bins=30, density=True)
ax.set_title(f'n = {n}')
plt.tight_layout(); plt.show()

# b
plt.figure(figsize=(7, 4))
for n in n_werte:
    stichprobe = np.random.binomial(n, p, size=10000)
    erwartung = n * p
    streuung = np.sqrt(n * p * (1 - p))
    z = (stichprobe - erwartung) / streuung
    plt.hist(z, bins=30, density=True, alpha=0.5, label=f'n = {n}')
plt.xlabel('$z$'); plt.ylabel('Dichte')
plt.legend(); plt.tight_layout(); plt.show()

#c
z_werte = np.linspace(-4, 4, 200)
dichte_standard = 1 / np.sqrt(2 * np.pi) * np.exp(-z_werte**2 / 2)

plt.figure(figsize=(7, 4))
for n in n_werte:
    stichprobe = np.random.binomial(n, p, size=10000)
    erwartung = n * p
    streuung = np.sqrt(n * p * (1 - p))
    z = (stichprobe - erwartung) / streuung
    plt.hist(z, bins=30, density=True, alpha=0.5, label=f'n = {n}')
plt.plot(z_werte, dichte_standard, 'k-', linewidth=2, label='Standardnormalverteilung')
plt.xlabel('$z$'); plt.ylabel('Dichte')
plt.legend(); plt.tight_layout(); plt.show()

#d
n_werte_2 = [1, 2, 5, 30]
mittelwert_uniform = 0.5
varianz_uniform = 1 / 12

plt.figure(figsize=(7, 4))
for n in n_werte_2:
    stichprobe = np.random.uniform(0, 1, size=(10000, n))
    S_n = stichprobe.sum(axis=1)
    erwartung = n * mittelwert_uniform
    streuung = np.sqrt(n * varianz_uniform)
    z = (S_n - erwartung) / streuung
    plt.hist(z, bins=30, density=True, alpha=0.5, label=f'n = {n}')
plt.plot(z_werte, dichte_standard, 'k-', linewidth=2, label='Standardnormalverteilung')
plt.xlabel('$z$'); plt.ylabel('Dichte')
plt.legend(); plt.tight_layout(); plt.show()