Computing Pearson Correlation from Component and Sum Variances
Easy · Statistics & Math · Data Scientist · Technical Screen
Problem Statement
Consider two real-valued random variables X and Y defined on the same probability space. You are given the variance of their sum var_sum = Var(X + Y), the variance of the first variable var_x = Var(X), and optionally the variance of the second variable var_y = Var(Y) (None when Var(Y) is unavailable).
Implement correlation_from_variances(var_sum, var_x, var_y) to compute the Pearson correlation coefficient between X and Y according to the following rules:
- Missing second variance (
var_y is None): Knowing onlyVar(X + Y)andVar(X)leaves bothVar(Y)andCov(X, Y)unknown inside a single equation, so correlation cannot be uniquely pinned down. After validating thatvar_sumandvar_xare finite and non-negative, returnNone. - Known positive variances (
var_x > 0andvar_y > 0): Use the sum-variance relationVar(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)to solve forCov(X, Y)and normalize bysqrt(Var(X)) * sqrt(Var(Y))(note that in the equal-variance caseVar(Y) == Var(X), this simplifies toVar(X + Y) / (2 * Var(X)) - 1). - Zero-variance variables (
var_x == 0orvar_y == 0): A constant random variable has zero covariance with every variable, forcingVar(X + Y) == Var(X) + Var(Y)(up to floating-point relative tolerance1e-9). If that equality holds, returnNonebecause Pearson correlation divides by zero; otherwise raise aValueError. - Input validation and feasibility: Raise a
ValueErrorif any supplied variance isNaN, infinite, or negative, or if the implied correlation magnitude exceeds1beyond benign floating-point rounding (1e-9). Clamp tiny rounding overshoots at the±1boundaries into[-1.0, 1.0].
Examples
Example 1
Input: var_sum = 57, var_x = 16, var_y = 25
Output: 0.4
Walk-through: Subtracting the individual variances from the sum variance gives 2 * Cov(X, Y) = 57 - 16 - 25 = 16, so Cov(X, Y) = 8.0. Dividing by sqrt(16) * sqrt(25) = 4 * 5 = 20 yields 8.0 / 20 = 0.4.
Example 2
Input: var_sum = 29, var_x = 16, var_y = 25
Output: -0.3
Walk-through: Because 29 is below the uncorrelated sum 16 + 25 = 41, the variables partly offset one another: Cov(X, Y) = (29 - 41) / 2 = -6.0, giving -6.0 / (4 * 5) = -0.3.
Example 3
Input: var_sum = 27, var_x = 9, var_y = 9
Output: 0.5
Walk-through: Here X and Y share equal variance V = 9, so Var(X + Y) / (2 * V) - 1 = 27 / 18 - 1 = 0.5.
Example 4
Input: var_sum = 20, var_x = 9, var_y = None
Output: None
Walk-through: Both 20 and 9 are finite and non-negative, and because var_y is None, infinitely many (Var(Y), Cov(X, Y)) pairs fit the inputs, so the function returns None.
Constraints
- All provided float arguments may span extreme IEEE-754 scales (e.g.,
1e-300through1e308), as well as0.0, negative numbers,inf, ornan. - Avoid intermediate floating-point overflow or underflow when multiplying or summing extreme variances.
- Any returned float correlation must lie in
[-1.0, 1.0].
Step-by-step walkthrough
Understand the statistical definitions and contract
Before touching algebra, let's pin down the four statistical quantities in plain English:
- Variance (
Var(X)): the average squared distance ofXfrom its mean — always>= 0. - Standard deviation (
sd_x = sqrt(Var(X))): the square root of variance, measuring spread in the original units ofX. - Covariance (
Cov(X, Y)): the average product(X - mean_x) * (Y - mean_y)— positive whenXandYrise together, negative when one rises as the other falls, and0when one is constant or they are uncorrelated. - Pearson correlation (
rho): covariance rescaled by both standard deviations so it always sits between-1and+1:
rho = Cov(X, Y) / (sd_x * sd_y)Our function
correlation_from_variances(var_sum, var_x, var_y)receivesVar(X + Y),Var(X), and optionallyVar(Y)(Noneif unknown), and obeys four clean rules:- If
var_y is None(Part 1), returnNonebecauserhocannot be uniquely determined. - If all three positive variances are consistent (Parts 2 and 3), return
rhoin[-1.0, 1.0]. - If
var_x == 0orvar_y == 0on consistent inputs, returnNonebecause dividing by0leavesrhoundefined. - If any variance is negative, non-finite (
NaN/inf), or violates mathematical bounds, raiseValueError.
- Variance (
Part 1: Why Var(X + Y) and Var(X) alone are not enough
The fundamental identity linking the variance of a sum to individual variances is:
Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)Why is there a
2 * Cov(X, Y)term? Because squaring(X - mean_x) + (Y - mean_y)expands just like(a + b)^2 = a^2 + b^2 + 2ab!If you are only told
Var(X + Y)andVar(X), you have one equation with two unknowns (Var(Y)andCov(X, Y)). Look how the exact same inputsVar(X) = 1andVar(X + Y) = 4produce three completely opposite correlations:Choice of Y Var(X) Var(Y) Cov(X, Y) Var(X + Y) rho ----------------------------- ------ ------ --------- ---------- ----- Y = X (moves with X) 1 1 +1 4 +1.0 Y indep of X (unrelated) 1 3 0 4 0.0 Y = -3 * X (opposes X) 1 9 -3 4 -1.0So Part 1's answer is No: we additionally need
Var(Y)(or another second-moment piece likeVar(X - Y)plusVar(Y)). Notice that anyvar_sum >= 0andvar_x >= 0can be realized by someY, so after checking finiteness and non-negativity,var_y is Noneimmediately returnsNone:# Phase 1: Validate known variances (reject NaN, Inf, and negative values). if not math.isfinite(var_sum) or not math.isfinite(var_x): raise ValueError("variances must be finite") if var_sum < 0 or var_x < 0: raise ValueError("a variance cannot be negative") # Part 1: Without Var(Y), one equation has two unknowns (Var(Y) and Cov(X, Y)), so rho is unidentifiable. if var_y is None: return None if not math.isfinite(var_y) or var_y < 0: raise ValueError("variances must be finite and non-negative")Part 2: Derive correlation when Var(Y) is also known
Once
Var(Y)is also given,Cov(X, Y)is the only unknown left in the sum identity! Solve forCov(X, Y)in two algebra steps, then divide bysd_x * sd_y:Step 1: Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) Step 2: Cov(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / 2 = 0.5 * Var(X + Y) - 0.5 * Var(X) - 0.5 * Var(Y) Step 3: rho = Cov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y)))Read this formula intuitively using
Var(X) + Var(Y)as the uncorrelated baseline:Var(X + Y) > Var(X) + Var(Y)->XandYamplify each other ->rho > 0.Var(X + Y) == Var(X) + Var(Y)->XandYare uncorrelated ->rho == 0.Var(X + Y) < Var(X) + Var(Y)->XandYpartially cancel ->rho < 0.
# Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y). # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308. cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300. sd_x = math.sqrt(var_x) sd_y = math.sqrt(var_y) rho = cov / (sd_x * sd_y)Part 3: Simplify the equal-variance special case
In the special case
Var(Y) = Var(X) = V(withV > 0), both standard deviations equalsqrt(V), sosd_x * sd_y = V:rho = (Var(X + Y) - V - V) / (2 * V) = (Var(X + Y) - 2 * V) / (2 * V) = Var(X + Y) / (2 * V) - 1Sanity-check the three landmark cases:
Y = -X (perfect cancellation): Var(X + Y) = 0 -> 0 / (2V) - 1 = -1.0 Y indep (uncorrelated): Var(X + Y) = 2 * V -> 2V / (2V) - 1 = 0.0 Y = +X (perfect reinforcement): Var(X + Y) = 4 * V -> 4V / (2V) - 1 = +1.0Our general Part 2 formula already evaluates to this exact number whenever
var_x == var_y, so no separate code path is needed.Handle degenerate, inconsistent, and extreme float inputs
A production-ready implementation must guard against four tricky numerical cases:
- Impossible variance triples (
|rho| > 1): By the Cauchy-Schwarz inequality (a mathematical bound guaranteeing|Cov(X, Y)| <= sd_x * sd_y),Var(X + Y)must always lie inside:
[(sd_x - sd_y)^2, (sd_x + sd_y)^2]For `Var(X) = 4` (`sd_x = 2`) and `Var(Y) = 9` (`sd_y = 3`), `Var(X + Y)` must sit in `[1, 25]`; `var_sum = 30` implies `rho = 1.417`, which no random variables can ever have, so we raise `ValueError`.- Floating-point rounding at
±1: Valid inputs likevar_x = 2, var_y = 3, var_sum = (sqrt(2) + sqrt(3))^2can evaluate torho = 1.0000000000000002in 64-bit float. Allowing a tinyTOLERANCE = 1e-9before raising and then clampingmax(-1.0, min(1.0, rho))keeps exact boundary cases valid. - Zero variance (
var_x == 0orvar_y == 0): A constant never varies from its mean, so its covariance with anything is0, forcingVar(X + Y) == Var(X) + Var(Y). Ifvar_sumdisagrees, raiseValueError; otherwise returnNone(0 / 0is undefined). - Preventing
1e308overflow and1e-300underflow: Writing0.5 * var_sum - 0.5 * var_x - 0.5 * var_yprevents-var_x - var_yfrom overflowing to-infwhenvar_x = var_y = 1e308, and takingmath.sqrt(var_x) * math.sqrt(var_y)separately preventsvar_x * var_yfrom overflowing at1e200or underflowing to0.0at1e-300.
# Phase 2: Degenerate zero-variance check. # A constant variable has Cov(X, Y) = 0, so Var(X + Y) must equal Var(X) + Var(Y), while rho is 0/0 (None). if var_x == 0 or var_y == 0: expected_sum = var_x + var_y scale = max(var_sum, expected_sum) if abs(var_sum - expected_sum) > TOLERANCE * scale: raise ValueError("inconsistent: a constant variable has zero covariance") return None # Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y). # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308. cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300. sd_x = math.sqrt(var_x) sd_y = math.sqrt(var_y) rho = cov / (sd_x * sd_y) # Phase 4: Enforce Cauchy-Schwarz (|rho| <= 1) up to float rounding, then clamp into [-1.0, 1.0]. if abs(rho) > 1.0 + TOLERANCE: raise ValueError("inconsistent variances: |rho| would exceed 1") return max(-1.0, min(1.0, rho))- Impossible variance triples (
Walk through the four examples
Example (var_sum, var_x, var_y) cov = 0.5*(sum - x - y) sd_x * sd_y Result ------- ----------------------- ------------------------ ----------- ------ 1 (57, 16, 25) 0.5*(57 - 16 - 25) = 8.0 4 * 5 = 20 0.4 2 (29, 16, 25) 0.5*(29 - 16 - 25) = -6.0 4 * 5 = 20 -0.3 3 (27, 9, 9) 0.5*(27 - 9 - 9) = 4.5 3 * 3 = 9 0.5 4 (20, 9, None) var_y missing -> unidentifiable NoneIn Examples 1 and 2,
var_sumsits inside the valid range[(4 - 5)^2, (4 + 5)^2] = [1, 81], landing above the uncorrelated sum16 + 25 = 41in Example 1 (rho = +0.4) and below41in Example 2 (rho = -0.3).Full solution
from typing import Any, Dict, List, Optional, Set, Tuple import math # Small relative slack so exact |rho| = 1 inputs nudged by float rounding (e.g. 1.0000000000000002) pass. TOLERANCE = 1e-9 def correlation_from_variances( var_sum: float, var_x: float, var_y: Optional[float] ) -> Optional[float]: # Phase 1: Validate known variances (reject NaN, Inf, and negative values). if not math.isfinite(var_sum) or not math.isfinite(var_x): raise ValueError("variances must be finite") if var_sum < 0 or var_x < 0: raise ValueError("a variance cannot be negative") # Part 1: Without Var(Y), one equation has two unknowns (Var(Y) and Cov(X, Y)), so rho is unidentifiable. if var_y is None: return None if not math.isfinite(var_y) or var_y < 0: raise ValueError("variances must be finite and non-negative") # Phase 2: Degenerate zero-variance check. # A constant variable has Cov(X, Y) = 0, so Var(X + Y) must equal Var(X) + Var(Y), while rho is 0/0 (None). if var_x == 0 or var_y == 0: expected_sum = var_x + var_y scale = max(var_sum, expected_sum) if abs(var_sum - expected_sum) > TOLERANCE * scale: raise ValueError("inconsistent: a constant variable has zero covariance") return None # Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y). # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308. cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300. sd_x = math.sqrt(var_x) sd_y = math.sqrt(var_y) rho = cov / (sd_x * sd_y) # Phase 4: Enforce Cauchy-Schwarz (|rho| <= 1) up to float rounding, then clamp into [-1.0, 1.0]. if abs(rho) > 1.0 + TOLERANCE: raise ValueError("inconsistent variances: |rho| would exceed 1") return max(-1.0, min(1.0, rho))✅ Submit now — all tests should pass.
Intuition & how it works
Think of two random variables X and Y as two ocean waves meeting on the water, where variance (the average squared distance from the mean) measures each wave's energy. If two unrelated waves of energies 16 and 25 meet randomly, their combined wave X + Y has baseline energy 16 + 25 = 41. When the combined wave carries more energy than 41 (say 57), their peaks are lining up together (positive correlation); when it is calmer than 41 (say 29), the two waves are partially canceling each other out (negative correlation).
If you are only given Var(X + Y) and Var(X), trying to write a formula for correlation fails immediately because one equation (Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)) cannot solve for two unknowns (Var(Y) and Cov(X, Y)). Even once Var(Y) is provided, a bare one-liner (var_sum - var_x - var_y) / (2 * sqrt(var_x * var_y)) breaks on edge inputs: it crashes with division by zero on constant variables, returns impossible numbers like 1.42 on inconsistent variances, falsely rejects valid rho = 1 inputs nudged to 1.0000000000000002 by float rounding, and overflows var_x * var_y at 1e200 (or -var_x - var_y at 1e308).
Walking through Example 1 (var_sum=57, var_x=16, var_y=25) step by step:
- Extract covariance: Covariance measures how
XandYco-move in raw units; subtracting the uncorrelated baseline16 + 25 = 41and halving givesCov(X, Y) = 0.5 * 57 - 0.5 * 16 - 0.5 * 25 = 8.0. - Compute standard deviations: Each standard deviation (the square root of variance) is
sd_x = sqrt(16) = 4andsd_y = sqrt(25) = 5. - Normalize and validate: Pearson correlation divides covariance by
sd_x * sd_y = 20, givingrho = 8.0 / 20 = 0.4. Because|0.4| <= 1(satisfying the Cauchy-Schwarz inequality, which guarantees|Cov(X, Y)| <= sd_x * sd_y),0.4is valid and returned directly.
Complexity
- Time: O(1). Every call performs a fixed handful of finiteness checks, floating-point multiplications/subtractions, two square roots, and one division, with no loops or recursion.
- Space: O(1). Only a constant number of scalar floating-point variables (
cov,sd_x,sd_y,rho) are allocated.
Edge cases
- Missing
Var(Y)(var_y is None): ReturnsNoneafter verifyingvar_sumandvar_xare finite and non-negative; anyvar_sum >= 0is achievable by choosing a suitableY, so(var_sum, var_x)alone is never inconsistent. - Equal variances (
Var(X) = Var(Y) = V): Simplifies algebraically torho = Var(X + Y) / (2 * V) - 1, mappingVar(X + Y)linearly from[0, 4V]onto[-1, +1]. - Zero variance (
Var(X) = 0orVar(Y) = 0): A constant variable has zero covariance with everything, soVar(X + Y)must equalVar(X) + Var(Y)(otherwiseValueErroris raised), andrhois undefined (None) because its denominator is0. - Boundary rounding at
rho = ±1: Inputs likevar_x = 2, var_y = 3, var_sum = (sqrt(2) + sqrt(3))^2can round to1.0000000000000002; checkingabs(rho) > 1.0 + 1e-9and clamping to[-1.0, 1.0]accepts exact collinearity while rejecting genuine impossible triples. - Extreme float scales (
1e-300to1e308) andNaN/inf: Separatesqrtcalls and pre-halved0.5 * varterms prevent intermediate overflow/underflow, andmath.isfinitecatchesNaNandinfbefore comparisons silently pass.
Common mistakes
- Claiming
Var(X + Y)andVar(X)suffice whenVar(Y)is omitted: WithoutVar(Y),Var(X) = 1andVar(X + Y) = 4fitsrho = +1(Y = X),rho = 0(Var(Y) = 3independent), andrho = -1(Y = -3X). - Forgetting the factor of
2onCov(X, Y): WritingVar(X + Y) = Var(X) + Var(Y) + Cov(X, Y)makes every computed correlation twice as large as the true value. - Dividing by
Var(X) * Var(Y)or(Var(X) + Var(Y)) / 2: Correlation normalizes bysqrt(Var(X)) * sqrt(Var(Y)); the arithmetic mean(Var(X) + Var(Y)) / 2only matches the geometric mean whenVar(X) == Var(Y). - Skipping consistency checks: Blindly returning
rho = 1.42for(30, 4, 9)ignores thatVar(X + Y)must lie inside[(sd_x - sd_y)^2, (sd_x + sd_y)^2] = [1, 25]. - Computing
math.sqrt(var_x * var_y)as a single product:1e200 * 1e200overflows toinf(returningrho = 0.0instead of1.0!), while1e-200 * 1e-200underflows to0.0and raisesZeroDivisionError.
Follow-up questions
- How does the calculation behave when one of the two random variables has zero variance? A zero-variance variable takes a single constant value with probability
1, so it never deviates from its mean and its covariance with any random variable is0. That leavesrho = 0 / 0undefined (so our function returnsNone, whereas NumPy returnsnan), and it enforces a strict consistency check:Var(X + Y)must equalVar(X) + Var(Y), or else we raiseValueError. - If you were given the variance of the difference X - Y in place of the sum X + Y, how would the expression for correlation change? Replacing
+Ywith-Yflips the sign on the cross-term:Var(X - Y) = Var(X) + Var(Y) - 2 * Cov(X, Y). Rearranging and normalizing yieldsrho = (Var(X) + Var(Y) - Var(X - Y)) / (2 * sd_x * sd_y)— here, strong positive correlation shrinksVar(X - Y)becauseXandYmove together and cancel in the difference! Better yet, if you know bothVar(X + Y)andVar(X - Y)for equal-variance variables,Var(X)cancels out completely to giverho = (Var(X + Y) - Var(X - Y)) / (Var(X + Y) + Var(X - Y)). - Could you construct two concrete pairs of random variables that share identical values of Var(X) and Var(X + Y) yet exhibit completely different correlations? Let
Xtake+1and-1with probability1/2each, soVar(X) = 1, and targetVar(X + Y) = 4. Pair A setsY = X: thenX + Y = 2XhasVar(X + Y) = 4withrho = +1. Pair B setsY = -3X: thenX + Y = -2Xstill hasVar(X + Y) = (-2)^2 * 1 = 4, yetYmoves strictly opposite toXwithrho = -1! - What practical issues arise when plugging noisy sample variance estimates into this identity instead of exact population variances? When
Var(X + Y),Var(X), andVar(Y)are computed from the exact same complete paired sample with the same denominator (norn - 1), the algebraic identity still holds on the sample and matches sample Pearsonrinside[-1, 1]. If instead the three variances come from different lookback windows, missing-data subsets, or asynchronous ticks (common in market data), independent estimation noise no longer cancels and can push the implied correlation outside[-1, 1]. To quantify sampling uncertainty fromnpaired observations, apply the Fisher z-transform (z = 0.5 * ln((1 + r) / (1 - r)), a nonlinear mapping that makes sample correlation roughly normal with standard error1 / sqrt(n - 3)), build a confidence interval inz-space, and transform back to[-1, 1].
Follow-up questions
- How does the calculation behave when one of the two random variables has zero variance?
- If you were given the variance of the difference X - Y in place of the sum X + Y, how would the expression for correlation change?
- Could you construct two concrete pairs of random variables that share identical values of Var(X) and Var(X + Y) yet exhibit completely different correlations?
- What practical issues arise when plugging noisy sample variance estimates into this identity instead of exact population variances?
Similar questions
- Identifiability and Derivation of Correlation from Variance Terms
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations
- Impact of Dataset Duplication on OLS and Large-Sample Inference