Question
This was the coding question in a technical phone screen. Given a continuous probability density function (PDF) , derive or implement its cumulative distribution function (CDF):
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: is the density mass to the left of . What does that area do far to the left, far to the right, and when crosses a point where changes formula?
Hint 2
With a formula, integrate one piece at a time in increasing . In code you can only evaluate , 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
and.
TIP
How I'd say it in the interview: "The CDF at is the area under the density left of : 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 , and interpolate."
Then walk through:
- Area reading, and the density conditions: never negative, total area
. - Boundary behavior:
,, never decreasing, continuous. - Piecewise derivation, carrying the earlier mass.
- Trapezoid accumulation on a grid from
. Most candidates lose points here, by summing density values without the step width. - Total check, interpolated queries, and a test against the hand-derived CDF.
Solution
is the area under left of : before the support, after it, never decreasing, continuous, with slope . Each piece of a piecewise starts from the mass of the earlier pieces. In code, evaluate 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 is probability per unit length, not a probability. Only areas under it are probabilities.
Normalization: two conditions make a density, everywhere and a total area of . The first makes never decrease, because moving right only adds nonnegative area. The second makes end at . If the density is known only up to a constant, as , set . For on the area is , so .
Support: the support is where . Left of it no area has been collected, so . Right of it all the area has been collected, so . For an unbounded support these become limits: as and as .
Continuity and slope: moving from to adds a thin strip of area, about , which shrinks to with . So has no jumps, even where jumps. Dividing the strip by its width gives , so wherever is continuous. Where jumps, only changes slope.
NOTE
A single point carries probability , so . Which piece owns a breakpoint, or , does not change .
Piecewise PDF, piecewise CDF
Suppose has breakpoints and formula on . For in that piece, split the integral at . Everything left of is already , and only the area from to is new:
Compute 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:
It is never negative, and its area is from the flat part plus from the triangle (base , height ), so it is a valid density.
Left of , . On the area up to is a rectangle of height , so and . On , apply the rule with : start from and add the ramp's area from to . The antiderivative of is . Subtract its value at , which is , from its value at , then put everything over :
The last form is minus the triangle right of . Check: gives , matching the first piece, and gives . Right of , . Together:

Compare the two panels at : the shaded area is , the height of the CDF there. At the density jumps from to , 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 across the support with spacing . Over one step, the area is close to a trapezoid with parallel sides and :
approximates , and because the grid starts at the left edge of the support. A cumulative sum computes every in one pass.

Here the running totals match the exact CDF, because the density is straight between grid points. For a curved density the error shrinks like , so halving the spacing cuts it by about .
Edge cases in code
Three details remain:
- Queries: interpolate linearly between grid points, and return
left of the grid andright of it.np.interpholds the end values, so it does both. - Unbounded support: cut the grid where the tail is negligible. A standard normal has about
of its mass beyond. - Normalization: divide by the last running total to remove the small discretization error, but only after checking it is close to
.
WARNING
Normalizing without that check hides a bug. A grid on for a standard normal collects of the mass. Dividing by it makes the table end at , but reports instead of . A total far from 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 , 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 overit ends near, not. - Forgetting the mass of earlier pieces. Integrating the ramp from
alone givesinstead of, and the CDF drops fromtoat. - Applying a piece's formula outside its interval.
atgives, andatgives, below.
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
-th quantile is, andwithuniform onis a sample. With the table, swap the arrays:np.interp(p, F, x). The illustrative 90th percentile solves, so. - "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.