Code
import numpy as np
import matplotlib.pyplot as plt
# Example: k successes out of n trials
n = 40
k = 12
p_grid = np.linspace(0.001, 0.999, 400)
# Log-likelihood (up to an additive constant)
log_L = k * np.log(p_grid) + (n - k) * np.log(1 - p_grid)
# Rescaled likelihood to avoid overflow and keep it on a nice scale
L = np.exp(log_L - log_L.max())
p_hat = k / n
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
# Left: likelihood
ax = axes[0]
ax.plot(p_grid, L)
ax.axvline(p_hat, linestyle="--")
ax.set_xlabel("p")
ax.set_ylabel("L(p)")
ax.set_title("Likelihood for Bernoulli p")
# Right: log-likelihood
ax = axes[1]
ax.plot(p_grid, log_L)
ax.axvline(p_hat, linestyle="--")
ax.set_xlabel("p")
ax.set_ylabel("log L(p)")
ax.set_title("Log-likelihood for Bernoulli p")
fig.suptitle("Same MLE $\hat p$ from L(p) and log L(p)", y=1.02)
fig.tight_layout()
plt.show()




