KatInterview

Delta-Method Variance of a Ratio of Two Sample Means

Math & Bit ManipulationAuto-graded · 19 test cases
MediumAuto-gradedMath & Bit Manipulationdelta-methodvariancecovariance

Last updated

Apply a first-order Taylor expansion to get the approximate variance of a ratio of two correlated sample means, including the covariance term.

An experiment dashboard reports a ratio metric: the average of a numerator quantity (such as revenue per bucket) divided by the average of a denominator quantity (such as active users per bucket). Both averages are taken over the same n independent buckets, and the two per-bucket quantities are correlated.

Write a function that returns the first-order (delta-method) approximation of the variance of this ratio of sample means.

Inputs

  • num_mean: the mean of the per-bucket numerator quantity.
  • den_mean: the mean of the per-bucket denominator quantity.
  • num_var: the per-bucket variance of the numerator quantity.
  • den_var: the per-bucket variance of the denominator quantity.
  • corr: the correlation between the numerator and denominator quantities within a bucket.
  • n: the number of buckets.

Task

Let the ratio be R = (sample mean of numerator) / (sample mean of denominator). Linearize g(x, y) = x / y around (num_mean, den_mean), using the gradient evaluated there.

  1. Compute the per-bucket covariance as corr * sqrt(num_var * den_var).

  2. Compute the per-bucket variance of the linearized ratio:

    num_var / den_mean^2 + num_mean^2 * den_var / den_mean^4 - 2 * num_mean * covariance / den_mean^3

  3. Because the means are taken over n independent buckets, divide this by n.

Return the result as a float. Do not round it. The covariance term is subtracted, as the formula above shows.

Constraints

  • den_mean != 0
  • num_var >= 0 and den_var >= 0
  • -1 <= corr <= 1
  • n >= 1 (integer)
  • The inputs are plain numbers. No input validation is required.

Examples

Example 1

Input: approximate_ratio_variance(100, 20, 400, 4, 0.6, 100)

Output: 0.006500000000000001

Example 2

Input: approximate_ratio_variance(250, 50, 900, 9, 0.6, 500)

Output: 0.00046799999999999994

Example 3

Input: approximate_ratio_variance(80, 10, 64, 1, 0, 100)

Output: 0.0128

Hints

Hint 1

The gradient of x/y at (mx, my) is (1/my, -mx/my^2). The variance of the linearized ratio is a quadratic form: gradient transposed times the covariance matrix times gradient.

Hint 2

Expand the quadratic form into three terms: var_x/my^2, mx^2*var_y/my^4, and a cross term with a minus sign, -2*mx*cov/my^3. Get the covariance from corr * sqrt(var_x * var_y).

Hint 3

These terms describe a single bucket. The statistic is a mean over n independent buckets, so divide the whole expression by n at the end.