def test_pdf(rng, allclose): s = 0.25 f = lambda x: ( np.exp(-0.5 * (x + 0.5) ** 2 / s ** 2) + np.exp(-0.5 * (x - 0.5) ** 2 / s ** 2) ) xref = np.linspace(-2, 2, 101) pref = f(xref) pref /= pref.sum() dist = PDF(xref, pref) n = 100000 samples = dist.sample(n, rng=rng) h, xedges = np.histogram(samples, bins=101) x = 0.5 * (xedges[:-1] + xedges[1:]) dx = np.diff(xedges) y = h / float(h.sum()) / dx z = f(x) z = z / z.sum() / dx assert allclose(y, z, atol=0.05) with pytest.raises(ValidationError, match="PDF must sum to one"): dist = PDF([0, 1, 2], [0.1, 1.1, 0.1]) with pytest.raises(ValidationError, match="`x` and `p` must be the same length"): dist = PDF([0, 1], [0, 1, 0])
def test_pdf(rng): s = 0.25 f = lambda x: (np.exp(-0.5 * (x + 0.5)**2 / s**2) + np.exp(-0.5 * (x - 0.5)**2 / s**2)) xref = np.linspace(-2, 2, 101) pref = f(xref) pref /= pref.sum() dist = PDF(xref, pref) n = 100000 samples = dist.sample(n, rng=rng) h, xedges = np.histogram(samples, bins=101) x = 0.5 * (xedges[:-1] + xedges[1:]) dx = np.diff(xedges) y = h / float(h.sum()) / dx z = f(x) z = z / z.sum() / dx assert np.allclose(y, z, atol=0.05)