Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

Question

This was the coding question in a technical phone screen. Given a continuous probability density function (PDF) f(x)f(x), derive or implement its cumulative distribution function (CDF):

F(x)=P(X≤x)=∫−∞xf(t) dtF(x) = P(X \le x) = \int_{-\infty}^{x} f(t)\,dt

Explain the support, the boundary behavior, the normalization requirement, and how a piecewise PDF leads to a piecewise CDF.

Hint 1

Read the integral as an area: F(x)F(x) is the density mass to the left of xx. What does that area do far to the left, far to the right, and when xx crosses a point where ff changes formula?

Hint 2

With a formula, integrate one piece at a time in increasing xx. In code you can only evaluate ff, so build the area one thin strip at a time on a grid over the support.

How to Answer in the Interview

A short question with a calculus core and a coding finish. The definition is given, so the points go to its properties and to code that is right the first time. Say the plan before typing.

Clarify first:

  • "Is the PDF a Python function, values on a grid, or a formula?" A function or grid needs numerical integration, a formula can be integrated by hand, and a discrete distribution needs only a cumulative sum.
  • "What is the support?" It sets the integration range and where the CDF is pinned at 00 and 11.

TIP

How I'd say it in the interview: "The CDF at xx is the area under the density left of xx: zero before the support, one after it, never decreasing. Each piece of a piecewise density adds to the mass already collected. In code I take a cumulative sum of trapezoid areas on a fine grid, check the total is 11, and interpolate."

Then walk through:

  1. Area reading, and the density conditions: never negative, total area 11.
  2. Boundary behavior: 00, 11, never decreasing, continuous.
  3. Piecewise derivation, carrying the earlier mass.
  4. Trapezoid accumulation on a grid from 00. Most candidates lose points here, by summing density values without the step width.
  5. Total check, interpolated queries, and a test against the hand-derived CDF.

Solution

F(x)F(x) is the area under ff left of xx: 00 before the support, 11 after it, never decreasing, continuous, with slope ff. Each piece of a piecewise FF starts from the mass of the earlier pieces. In code, evaluate ff on a grid, build a table of running trapezoid areas in O(n) time, and answer each query by interpolation, a binary search in O(log n).

Support, boundaries, and normalization

The density f(x)f(x) is probability per unit length, not a probability. Only areas under it are probabilities.

Normalization: two conditions make ff a density, f(x)≥0f(x)\ge 0 everywhere and a total area of 11. The first makes FF never decrease, because moving xx right only adds nonnegative area. The second makes FF end at 11. If the density is known only up to a constant, as c g(x)c\,g(x), set c=1/∫gc=1/\int g. For g(x)=3−xg(x)=3-x on [1,3][1,3] the area is 22, so c=1/2c=1/2.

Support: the support is where f>0f>0. Left of it no area has been collected, so F(x)=0F(x)=0. Right of it all the area has been collected, so F(x)=1F(x)=1. For an unbounded support these become limits: F(x)→0F(x)\to 0 as x→−∞x\to-\infty and F(x)→1F(x)\to 1 as x→+∞x\to+\infty.

Continuity and slope: moving from xx to x+δx+\delta adds a thin strip of area, about f(x) δf(x)\,\delta, which shrinks to 00 with δ\delta. So FF has no jumps, even where ff jumps. Dividing the strip by its width gives (F(x+δ)−F(x))/δ≈f(x)(F(x+\delta)-F(x))/\delta\approx f(x), so F′(x)=f(x)F'(x)=f(x) wherever ff is continuous. Where ff jumps, FF only changes slope.

NOTE

A single point carries probability 00, so P(X≤x)=P(X<x)P(X\le x)=P(X<x). Which piece owns a breakpoint, x<1x<1 or x≤1x\le 1, does not change FF.

Piecewise PDF, piecewise CDF

Suppose ff has breakpoints a0<a1<⋯<ama_0<a_1<\dots<a_m and formula fjf_j on [aj,aj+1)[a_j,a_{j+1}). For xx in that piece, split the integral at aja_j. Everything left of aja_j is already F(aj)F(a_j), and only the area from aja_j to xx is new:

F(x)=F(aj)+∫ajxfj(t) dt,aj≤x<aj+1F(x) = F(a_j) + \int_{a_j}^{x} f_j(t)\,dt, \qquad a_j \le x < a_{j+1}

Compute F(a1),F(a2),…F(a_1), F(a_2),\dots in order, so the pieces join with no gap. The interview report gives no specific density, so take this illustrative one, flat then a ramp:

f(x)={1/2,0≤x<1,(3−x)/4,1≤x≤3,0,otherwise.f(x)=\begin{cases}
1/2, & 0\le x<1,\\
(3-x)/4, & 1\le x\le 3,\\
0, & \text{otherwise.}
\end{cases}

It is never negative, and its area is 1/21/2 from the flat part plus 1/21/2 from the triangle (base 22, height 1/21/2), so it is a valid density.

Left of 00, F(x)=0F(x)=0. On [0,1)[0,1) the area up to xx is a rectangle of height 1/21/2, so F(x)=x/2F(x)=x/2 and F(1)=1/2F(1)=1/2. On [1,3][1,3], apply the rule with aj=1a_j=1: start from F(1)=1/2F(1)=1/2 and add the ramp's area from 11 to xx. The antiderivative of (3−t)/4(3-t)/4 is (3t−t2/2)/4(3t-t^2/2)/4. Subtract its value at t=1t=1, which is (5/2)/4(5/2)/4, from its value at t=xt=x, then put everything over 88:

F(x)=12+[3t−t2/24]1x=12+3x−x2/24−5/24=12+6x−x2−58=1−(3−x)28F(x) = \frac{1}{2} + \left[\frac{3t - t^2/2}{4}\right]_{1}^{x} = \frac{1}{2} + \frac{3x - x^2/2}{4} - \frac{5/2}{4} = \frac{1}{2} + \frac{6x - x^2 - 5}{8} = 1 - \frac{(3-x)^2}{8}

The last form is 11 minus the triangle right of xx. Check: x=1x=1 gives 1/21/2, matching the first piece, and x=3x=3 gives 11. Right of 33, F(x)=1F(x)=1. Together:

F(x)={0,x<0,x/2,0≤x<1,1−(3−x)2/8,1≤x<3,1,x≥3.F(x)=\begin{cases}
0, & x<0,\\
x/2, & 0\le x<1,\\
1-(3-x)^2/8, & 1\le x<3,\\
1, & x\ge 3.
\end{cases}

Two stacked charts of the illustrative density. Top: the PDF, flat at 1/2 on 0 to 1, then a straight ramp down to 0 at 3, with the area from 0 to 2 shaded and labeled 7/8. Bottom: the CDF, rising as x/2 to 1/2 at x = 1, then curving up to 1 at x = 3 and staying flat, with the point F(2) = 7/8 marked. The shaded area on top equals the height of the CDF below.

Compare the two panels at x=2x=2: the shaded area is 1−1/8=7/81-1/8=7/8, the height of the CDF there. At x=0x=0 the density jumps from 00 to 1/21/2, and the CDF only bends, as the continuity argument predicts.

Turning the integral into code

In code there is usually no antiderivative, only a function to evaluate. Place grid points x0<⋯<xn−1x_0<\dots<x_{n-1} across the support with spacing hh. Over one step, the area is close to a trapezoid with parallel sides f(xk−1)f(x_{k-1}) and f(xk)f(x_k):

Fk=Fk−1+h f(xk−1)+f(xk)2,F0=0F_k = F_{k-1} + h\,\frac{f(x_{k-1}) + f(x_k)}{2}, \qquad F_0 = 0

FkF_k approximates F(xk)F(x_k), and F0=0F_0=0 because the grid starts at the left edge of the support. A cumulative sum computes every FkF_k in one pass.

The illustrative PDF on a coarse grid with spacing h = 0.5. Six trapezoids fill the area under the curve. Below, a table lists the running total F at each grid point: 0, 0.25, 0.5, 0.719, 0.875, 0.969 and 1, with the update rule: the new total is the old total plus h times the average of the left and right density values.

Here the running totals match the exact CDF, because the density is straight between grid points. For a curved density the error shrinks like h2h^2, so halving the spacing cuts it by about 44.

Edge cases in code

Three details remain:

  • Queries: interpolate linearly between grid points, and return 00 left of the grid and 11 right of it. np.interp holds the end values, so it does both.
  • Unbounded support: cut the grid where the tail is negligible. A standard normal has about 10−1510^{-15} of its mass beyond ±8\pm 8.
  • Normalization: divide by the last running total to remove the small discretization error, but only after checking it is close to 11.

WARNING

Normalizing without that check hides a bug. A grid on [−2,2][-2,2] for a standard normal collects 0.95450.9545 of the mass. Dividing by it makes the table end at 11, but reports F(1.96)=0.9976F(1.96)=0.9976 instead of 0.97500.9750. A total far from 11 means the grid misses part of the support or the input is not a density, so raise an error.

Code

The implementation expects pdf to accept a NumPy array and to be zero outside [lo, hi].

import numpy as np

def make_cdf(pdf, lo, hi, n=10_001):
    """CDF of a density that is zero outside [lo, hi]."""
    x = np.linspace(lo, hi, n)
    y = pdf(x)
    strips = (y[:-1] + y[1:]) / 2 * np.diff(x)  # trapezoid areas
    F = np.concatenate(([0.0], np.cumsum(strips)))  # F[0] = 0 at lo
    if abs(F[-1] - 1) > 1e-3:
        raise ValueError(f"density integrates to {F[-1]:.4f} on [{lo}, {hi}]")
    F = F / F[-1]  # remove the tiny discretization error

    def cdf(q):
        return np.interp(q, x, F)  # 0 left of lo, 1 right of hi
    return cdf

A test against the CDF derived by hand, including points outside the support.

def pdf(x):  # the illustrative density
    return np.where((x >= 0) & (x < 1), 0.5,
                    np.where((x >= 1) & (x <= 3), (3 - x) / 4, 0.0))

def exact_cdf(x):
    return np.where(x < 0, 0.0, np.where(x < 1, x / 2,
                    np.where(x < 3, 1 - (3 - x) ** 2 / 8, 1.0)))

cdf = make_cdf(pdf, 0, 3)
for q in (-1, 0.5, 1, 2, 2.5, 4):
    print(f"F({q}) = {cdf(q):.6f}   exact {exact_cdf(q):.6f}")
grid = np.linspace(-1, 4, 2001)
print(f"Largest error on [-1, 4]: {np.abs(cdf(grid) - exact_cdf(grid)).max():.1e}")

Output:

F(-1) = 0.000000   exact 0.000000
F(0.5) = 0.250000   exact 0.250000
F(1) = 0.500000   exact 0.500000
F(2) = 0.875000   exact 0.875000
F(2.5) = 0.968750   exact 0.968750
F(4) = 1.000000   exact 1.000000
Largest error on [-1, 4]: 3.7e-09

An unbounded support, truncated at ±8\pm 8, and the check rejecting a grid that is too narrow.

from scipy import stats

normal_cdf = make_cdf(stats.norm.pdf, -8, 8)  # mass beyond ±8 is about 1e-15
for q in (-1.96, 0, 1.96):
    print(f"F({q}) = {normal_cdf(q):.6f}   scipy {stats.norm.cdf(q):.6f}")

try:
    make_cdf(stats.norm.pdf, -2, 2)  # this grid misses part of the support
except ValueError as err:
    print("ValueError:", err)

Output:

F(-1.96) = 0.024998   scipy 0.024998
F(0) = 0.500000   scipy 0.500000
F(1.96) = 0.975002   scipy 0.975002
ValueError: density integrates to 0.9545 on [-2, 2]

Additional Notes

Common mistakes

  • Summing density values without the step width. np.cumsum(pdf(x)) treats each value as a probability, and on the 10,001-point grid over [0,3][0,3] it ends near 33343334, not 11.
  • Forgetting the mass of earlier pieces. Integrating the ramp from 11 alone gives F(2)=3/8F(2)=3/8 instead of 7/87/8, and the CDF drops from 1/21/2 to 00 at x=1x=1.
  • Applying a piece's formula outside its interval. x/2x/2 at x=−1x=-1 gives −1/2-1/2, and 1−(3−x)2/81-(3-x)^2/8 at x=4x=4 gives 7/87/8, below F(3)=1F(3)=1.

What this question tests

Whether you know the CDF is the running integral of the density, can state its properties, and can turn it into correct numerical code, edges included. Likely follow-ups:

  • "Now find a percentile, or sample from it." Both invert the CDF. The pp-th quantile is F−1(p)F^{-1}(p), and F−1(U)F^{-1}(U) with UU uniform on (0,1)(0,1) is a sample. With the table, swap the arrays: np.interp(p, F, x). The illustrative 90th percentile solves (3−x)2/8=0.1(3-x)^2/8=0.1, so x=3−0.8≈2.106x=3-\sqrt{0.8}\approx 2.106.
  • "Solve it another way." Call scipy.integrate.quad(pdf, lo, q) per query. It is accurate and accepts infinite limits, but each query pays for a full integration, while the table pays once.

Patterns to reuse

  • A running total of a rate, such as distance from speed, is a cumulative sum of strip areas starting at zero.
  • Test numerical code against a closed-form case, including inputs outside the domain.
Your progressLogin to save progress
Spot an issue or have a suggestion?