Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
a_u, b_u = 2, 5
def f_uniform(x):
x = np.asarray(x, dtype=float)
return np.where((x >= a_u) & (x <= b_u), 1 / (b_u - a_u), 0.0)
xs = np.linspace(a_u - 1, b_u + 1, 400)
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(xs, f_uniform(xs), color='black')
ax.set_ylim(0, 1 / (b_u - a_u) * 1.3)
ax.set_xlabel('$x$')
ax.set_ylabel('$f_X(x)$')
ax.set_title(f'Uniform({a_u},{b_u}) density')
plt.tight_layout()
plt.show()
total, _ = quad(f_uniform, a_u - 1, b_u + 1)
p_3_4, _ = quad(f_uniform, 3, 4)
print(f"total area: {total:.4f}")
print(f"P(3 <= X <= 4) = {p_3_4:.4f} (should be 1/3 = {1/3:.4f}, since [3,4] is 1/3 of [2,5])")total area: 1.0000
P(3 <= X <= 4) = 0.3333 (should be 1/3 = 0.3333, since [3,4] is 1/3 of [2,5])