EconBase
← Back to paper

$2B$ or Not $2B$: A Tale of Three Algorithms for Streaming: Covariance Estimation after Welford and Chan-Golub-LeVeque

Extracted main text — title through conclusion, appendix excluded. This is what our citation measures are computed over, published so the extraction can be checked by eye.

50,879 characters · 35 sections · 19 citation commands

Rendered from LaTeX for readability, not typeset faithfully. Citation keys are highlighted; maths is left as source; figures, tables and equation environments are summarised rather than reproduced; unrecognised commands are greyed out so nothing is silently dropped. Email addresses are removed.
center[center omitted — 416 chars of source]
abstractThree algorithms for computing the unbiased sample covariance matrix in a streaming or distributed setting are placed on a unified algebraic, numerical, and statistical foundation. The Gram algorithm, derived from the bariance reformulation of reichel2025bariance, maintains the running cross-product matrix $\mathbf{G}_t = \sum_{i=1}^{t}\mathbf{x}_i\mathbf{x}_i^\top$ and column-sum vector $\mathbf{s}_t = \sum_{i=1}^t \mathbf{x}_i$, yielding the unbiased covariance in $O(p^2)$ per update. The Welford algorithm welford1962 propagates a running mean and outer-product corrections, achieving the same asymptotic cost with provably better numerical stability under large data shifts. The Chan--Golub--LeVeque (CGL) algorithm chan1979 supports block-parallel merging via an exact combination formula, making it the natural choice for distributed and map-reduce architectures. All three produce the same estimator in exact arithmetic; their finite-precision behaviour differs markedly. Beyond runtime and numerical comparisons, we introduce a conformal prediction framework for streaming covariance estimation that yields finite-sample, distribution-free confidence sets for each entry of the covariance matrix at any step $t$ of the data stream. Experiments confirm that the Gram algorithm is fastest for batch computation, Welford is uniquely robust to catastrophic cancellation under large mean shifts, CGL is optimal for distributed settings, and conformal intervals achieve the nominal coverage level across all three algorithms.

\noindentMSC (2020): Primary 62H12; Secondary 62-08, 65F30, 65Y20.\\ Keywords: streaming covariance, online statistics, Welford algorithm, Chan--Golub--LeVeque, conformal prediction, numerical stability.

Introduction

Covariance estimation is a foundational task in statistics, machine learning, and signal processing. In the classical batch setting all $n$ observations reside in memory and the textbook formula

equation[equation omitted — 185 chars of source]

is applied once. Modern applications routinely violate the batch assumption: sensor streams, federated databases, and large language model training pipelines all generate data faster than can be accumulated. An online algorithm must update its estimate of $\bm{\Sigma}_t$ as each new observation $\mathbf{x}_t$ arrives, using $O(p^2)$ working memory and $O(p^2)$ work per update.

Three strategies address this problem, but a unified treatment covering algebraic equivalence, floating-point error analysis, and statistical uncertainty quantification has not previously appeared. We fill this gap.

\paragraph{The Gram (bariance) algorithm.} It is generally well known (e.g. reichel2025bariance) that the sample variance has an $O(n)$ computation via scalar sums, without explicit centering. Lifting this to the matrix case yields (ref), with the streaming update rule $\mathbf{G}_t \gets \mathbf{G}_{t-1} + \mathbf{x}_t\mathbf{x}_t^\top$ and $\mathbf{s}_t \gets \mathbf{s}_{t-1}+\mathbf{x}_t$. The on-demand formula $\widehat{\bm{\Sigma}}_t = (t\mathbf{G}_t - \mathbf{s}_t\mathbf{s}_t^\top)/[t(t-1)]$ executes in one level-3 BLAS call. Its weakness is catastrophic cancellation when the data mean is large relative to the variance: both $t\mathbf{G}_t$ and $\mathbf{s}_t\mathbf{s}_t^\top$ are $O(t^2\|\bar\mathbf{x}\|^2)$ while their difference is $O(t\|\bm{\Sigma}\|)$.

\paragraph{The Welford algorithm.} welford1962 proposed a shift-invariant one-pass recurrence for scalar variance, extended to covariance by chan1979. The algorithm maintains a running mean $\bm{\mu}_t$ and a matrix $\mathbf{M}_t$ of centred outer-product corrections, updating both in $O(p^2)$ per step. Because corrections are computed relative to the current mean, the method is immune to large constant shifts in the data.

\paragraph{The Chan--Golub--LeVeque (CGL) algorithm.} chan1979 introduced a binary merge formula for independently computed covariance summaries: given $(n_A,\bm{\mu}_A,\mathbf{M}_A)$ and $(n_B,\bm{\mu}_B,\mathbf{M}_B)$, the combined summary is computed exactly. This makes the algorithm tree-parallelisable and directly applicable to federated settings where nodes cannot share raw observations.

\paragraph{Conformal prediction for streaming covariance.} All three algorithms produce point estimates. To quantify uncertainty, we propose a split conformal prediction protocol vovk2005,angelopoulos2023 that constructs a finite-sample, distribution-free confidence interval for each entry $\Sigma_{kl}$ at every step $t \ge 2$ of the stream. The interval has guaranteed marginal coverage $1-\alpha$ for any $\alpha \in (0,1)$, with no distributional assumptions on the data. Experiments show that the coverage guarantee is tight across all three algorithms under well-conditioned data, but the Gram interval collapses (inflates catastrophically) under large data shifts, while Welford and CGL maintain valid coverage.

\paragraph{Contributions.}

enumerate• Complete algorithmic descriptions with proofs of correctness and three-way algebraic equivalence (Sections (ref)--(ref)). • A floating-point error analysis quantifying rounding accumulation and catastrophic cancellation for each algorithm (Section (ref)). • A split conformal prediction framework for streaming covariance entry estimation, with a finite-sample coverage guarantee (Section (ref)). • Benchmarks on x86-64 hardware with OpenBLAS covering runtime (varying $n$ and $p$), accuracy under Gaussian, heavy-tailed, ill-conditioned, and near-singular data, and conformal coverage under large shifts (Sections (ref)--(ref)). • A practitioner decision guide (Section (ref)).

Complete proofs for all results appear in Appendix (ref).

Notation and Setup

Let $\mathbf{x}_1,\mathbf{x}_2,\ldots$ be a stream of observations in $\mathbb{R}^p$, $p \ge 2$. After $t \ge 2$ steps the target is the unbiased sample covariance

equation[equation omitted — 204 chars of source]

We write $\mathbf{s}_t = \sum_{i=1}^t \mathbf{x}_i$, $\mathbf{G}_t = \sum_{i=1}^t \mathbf{x}_i\mathbf{x}_i^\top$, $\bm{\mu}_t = \mathbf{s}_t/t$, and $\mathbf{M}_t$ for the Welford/CGL correction matrix. The unit roundoff for IEEE 754 double precision is $\varepsilon_{\mathrm{mach}} = 2^{-53} \approx 1.11\times10^{-16}$. We write $\|\cdot\|_F$, $\|\cdot\|_2$, $\|\cdot\|_{\max}$ for the Frobenius, spectral, and entry-wise maximum norms. For a matrix $A$ the condition number is $\kappa(A) = \|A\|_2\|A^{-1}\|_2$.

Algorithms

Gram (Bariance) Algorithm

algorithm[algorithm omitted — 618 chars of source]
theorem[Gram identity] For any $\mathbf{x}_1,\ldots,\mathbf{x}_t\in\mathbb{R}^p$ with $t\ge 2$, \[ \bm{\Sigma}_t \;=\; \frac{t\mathbf{G}_t - \mathbf{s}_t\mathbf{s}_t^\top}{t(t-1)}. \]
proofSee Appendix (ref).

\noindentBLAS structure. Each update adds a rank-one correction to $\mathbf{G}$ (DSYR, level-2 BLAS) and a vector increment to $\mathbf{s}$ (DAXPY). Computing $\widehat{\bm{\Sigma}}_t$ on demand requires one outer product (DGER). In batch mode, replacing the loop with a single DSYRK call achieves the optimal level-3 BLAS structure.

Welford Algorithm

algorithm[algorithm omitted — 737 chars of source]
theorem[Welford invariant] After processing $\mathbf{x}_1,\ldots,\mathbf{x}_t$ via Algorithm (ref), \[ \mathbf{M}_t = \sum_{i=1}^t(\mathbf{x}_i - \bm{\mu}_t)(\mathbf{x}_i - \bm{\mu}_t)^\top. \] Hence $\widehat{\bm{\Sigma}}_t^{\mathrm{Welf}} = \bm{\Sigma}_t$.
proofSee Appendix (ref).

The critical property is that both $\bm{\Delta} = \mathbf{x}_t - \bm{\mu}_{t-1}$ and $\mathbf{x}_t - \bm{\mu}_t$ are computed as residuals from means of the same scale as the data, preventing cancellation regardless of the absolute value of $\bm{\mu}_t$.

Chan--Golub--LeVeque Algorithm

algorithm[algorithm omitted — 512 chars of source]
theorem[CGL correctness] Let $A,B$ be disjoint index sets. Define $\bm{\Delta} = \bm{\mu}_B - \bm{\mu}_A$. Then \[ \mathbf{M}_{A\cup B} = \mathbf{M}_A + \mathbf{M}_B + \frac{n_An_B}{n_A+n_B}\bm{\Delta}\bm{\Delta}^\top. \]
proofSee Appendix (ref).

Setting block size $b=1$ (each block is a single observation) recovers Algorithm (ref) exactly; block size $b=n$ recovers the batch formula (ref). Because the merge operation is associative and commutative, the algorithm can be applied in any binary-tree order, enabling map-reduce computation.

Algebraic Equivalence

theorem[Three-way equivalence in exact arithmetic] In exact arithmetic, $\widehat{\bm{\Sigma}}_t^{\mathrm{Gram}} = \widehat{\bm{\Sigma}}_t^{\mathrm{Welf}} = \widehat{\bm{\Sigma}}_t^{\mathrm{CGL}} = \bm{\Sigma}_t$ for all $t\ge 2$ and any block size $b\ge 1$ in the CGL algorithm.
proofGram equals $\bm{\Sigma}_t$ by Theorem (ref). Welford equals $\bm{\Sigma}_t$ by Theorem (ref). CGL with $b=1$ equals Welford by direct substitution: one observation $\mathbf{x}_t$ is a block with $n_B=1$, $\mathbf{M}_B=\mathbf{0}$, $\bm{\mu}_B=\mathbf{x}_t$, and the merge formula reduces to the Welford update. CGL with $b>1$ follows by induction on the tree using Theorem (ref).
remark[Bariance connection] For $p=1$, Theorem (ref) gives $\widehat{\bm{\Sigma}}_t = (tS_{xx} - S_x^2)/[t(t-1)]$, which is the bariance identity of reichel2025bariance. The Gram algorithm is the natural matrix extension of the bariance.

Floating-Point Error Analysis

All three algorithms are algebraically identical but differ in their numerical stability. We quantify two distinct phenomena: rounding accumulation over $t$ steps, and catastrophic cancellation induced by a non-zero data mean.

Rounding Accumulation

Write $\bar x = \|\bm{\mu}_t\|_\infty$ and $\sigma = \|\bm{\Sigma}_t\|_\infty^{1/2}$.

proposition[Gram rounding bound] Let $|x_{ik}|\le X$ for all $i,k$. The entry-wise error of the Gram estimator satisfies \[ \bigl|\widehat{\bm{\Sigma}}_{kl,t}^{\mathrm{Gram}} - \Sigma_{kl,t}\bigr| \;\lesssim\; X^2\varepsilon_{\mathrm{mach}} + \frac{\bar x^2}{t-1}\varepsilon_{\mathrm{mach}}. \]
proposition[Welford rounding bound] Under the same assumptions, \[ \bigl|\widehat{\bm{\Sigma}}_{kl,t}^{\mathrm{Welf}} - \Sigma_{kl,t}\bigr| \;\lesssim\; \sigma_k\sigma_l\varepsilon_{\mathrm{mach}}, \] independently of $\bar x$, where $\sigma_k^2 = \Sigma_{kk,t}$.
proposition[CGL rounding bound] For a balanced binary-tree merge of depth $\log_2 t$, \[ \bigl|\widehat{\bm{\Sigma}}_{kl,t}^{\mathrm{CGL}} - \Sigma_{kl,t}\bigr| \;\lesssim\; \sigma_k\sigma_l\varepsilon_{\mathrm{mach}}\log_2 t. \]

Proofs are given in Appendix (ref). The key contrast: Gram accumulates error at scale $X^2$ (the magnitude of raw observations), while Welford accumulates at scale $\sigma_k\sigma_l$ (the covariance of centred observations). The Welford bound is thus independent of the data mean, as formalised below.

Catastrophic Cancellation

proposition[Cancellation bound] Suppose $\mathbf{x}_i = \bm{\mu} + \mathbf{z}_i$ with $\|\bm{\mu}\|_2 = c$ and $\mathbf{z}_i\sim(0,\bm{\Sigma})$, $\|\bm{\Sigma}\|_2=\sigma^2$. Then \begin{align*} \left\lVert\widehat{\bm{\Sigma}}_t^{\mathrm{Gram}} - \bm{\Sigma}_t\right\rVert_F &\;\gtrsim\; pc^2\varepsilon_{\mathrm{mach}},\\ \left\lVert\widehat{\bm{\Sigma}}_t^{\mathrm{Welf}} - \bm{\Sigma}_t\right\rVert_F &= O(p\sigma^2\varepsilon_{\mathrm{mach}}), \end{align*} independently of $c$.
proofSee Appendix (ref).

For $c = 10^7$ and $\sigma=1$, the Gram bound gives $pc^2\varepsilon_{\mathrm{mach}} \approx p\cdot 10^{14}\cdot 10^{-16} = p\cdot 10^{-2}$, which becomes non-negligible relative to $\sigma^2=1$. At $c=10^{12}$, the error is $O(p\cdot 10^8)$, fully destroying the estimate (confirmed experimentally in Figure (ref)).

Summary of Bounds

table[table omitted — 686 chars of source]

Conformal Prediction for Streaming Covariance

Point estimates from any of the three algorithms carry no automatic uncertainty certificate. We now develop a finite-sample, distribution-free confidence interval for each covariance entry $\Sigma_{kl}$ at every step $t$ of the stream.

Background: Split Conformal Prediction

Split conformal prediction vovk2005,papadopoulos2002,angelopoulos2023 produces a $(1-\alpha)$-coverage prediction interval for a new observation using a held-out calibration set. Given calibration nonconformity scores $s_1,\ldots,s_m$, the conformal quantile is \[ \hat q_\alpha^+ = \mathrm{Quantile}\!\left(\{s_i\}_{i=1}^m;\, \frac{\lceil(m+1)(1-\alpha)\rceil}{m}\right), \] and the interval for a fresh test point has guaranteed marginal coverage $\Pr(\text{true value} \in \hat C_\alpha) \ge 1-\alpha$, with no distributional assumptions on $s_1,\ldots,s_m$ beyond exchangeability.

Protocol for Streaming Covariance

Fix target entry $(k,l)$, nominal coverage $1-\alpha$, and an algorithm $\mathcal{A}\in\{\text{Gram},\text{Welford},\text{CGL}\}$. Let $\Sigma_{kl}$ denote the true population covariance entry.

enumerate\itemCalibration. Draw $m$ independent calibration trajectories $\{\mathbf{x}_i^{(j)}\}_{i=1}^t$, $j=1,\ldots,m$, from the data-generating distribution. For each trajectory $j$ and each step $t$ of interest, compute \[ s_j(t) = \bigl|\mathcal{A}\bigl(\mathbf{x}_1^{(j)},\ldots,\mathbf{x}_t^{(j)}\bigr)_{kl} - \Sigma_{kl}\bigr|. \] \itemQuantile. Set $\hat q_\alpha^+(t) = \mathrm{Quantile}(\{s_j(t)\};\,\lceil(m+1)(1-\alpha)\rceil/m)$. \itemInterval. For a fresh test stream at step $t$, let $\hat\sigma_{kl}(t)$ be the algorithm's estimate. The conformal interval is $\hat C_\alpha(t) = [\hat\sigma_{kl}(t) - \hat q_\alpha^+(t),\; \hat\sigma_{kl}(t) + \hat q_\alpha^+(t)]$.
theorem[Finite-sample coverage] Under the assumption that calibration and test trajectories are i.i.d.\ (exchangeable), the conformal interval $\hat C_\alpha(t)$ satisfies \[ \Pr\!\bigl(\Sigma_{kl} \in \hat C_\alpha(t)\bigr) \;\ge\; 1-\alpha. \]
proofSee Appendix (ref). The proof applies the standard split-conformal coverage argument of vovk2005 with nonconformity score $s = |\hat\sigma_{kl}(t) - \Sigma_{kl}|$.
remark[Algorithm dependence of interval width] The coverage guarantee is algorithm-independent. However, the interval width $2\hat q_\alpha^+(t)$ reflects the variance of each estimator's error distribution. For Gram under large shift $c$, the calibration scores $s_j(t)$ are inflated by the cancellation term $O(c^2\varepsilon_{\mathrm{mach}})$, producing wide intervals or, if $c$ is not replicated in calibration, invalid coverage. Welford is immune to this effect.
remark[Unknown $\Sigma_{kl}$] In practice $\Sigma_{kl}$ is unknown, so calibration scores are computed using the batch reference on each calibration trajectory (which uses the full $m$ observations as ground truth). For large $m$ this reference converges to $\Sigma_{kl}$ at rate $O(m^{-1/2})$. Alternatively, one can treat the batch reference as the target and the interval inherits the same finite-sample guarantee relative to that target.

Computational Cost

table[table omitted — 699 chars of source]

The Gram algorithm is faster in batch mode than numpy.cov because it avoids forming and writing the centred matrix $\mathbf{X} - \mathbf{1}_n\bm{\mu}^\top$, saving $O(np)$ memory writes. In streaming mode, Welford computes two outer products per step (for $\bm{\Delta}$ and $\mathbf{x}_t - \bm{\mu}_t$) versus one for Gram, yielding a $\approx 2\times$ FLOP disadvantage; this gap is visible in practice when the outer product (DGER) is the bottleneck.

Experimental Protocol

\paragraph{Hardware and software.} All experiments ran on a macOS 13.0 ARM64 system with 10 CPU cores and OpenBLAS 0.3.31.188.0 via scipy-openblas (USE64BITINT, DYNAMIC_ARCH, NO_AFFINITY, neoversen1, MAX_THREADS=64) under Python 3.12.0 and NumPy 2.4.4 with a fixed random seed. All computations used IEEE 754 double precision.

\paragraph{Runtime measurement.} For each $( n, p )$ pair: (i) generate $\mathbf{X}\sim\mathcal{N}(0,I)$; (ii) run 3 warm-up calls; (iii) record 20--30 wall-clock times via time.perf_counter; (iv) remove outliers using the $1.5\times\mathrm{IQR}$ rule; (v) report the trimmed mean with a 95% bootstrap percentile interval (300 resamples).

\paragraph{Accuracy measurement.} For each data configuration the reference is numpy.cov. We report the entry-wise maximum error $\|\widehat{\bm{\Sigma}} - S_{\mathrm{ref}}\|_{\max}$ and the relative Frobenius error $\|\widehat{\bm{\Sigma}} - S_{\mathrm{ref}}\|_F/\|S_{\mathrm{ref}}\|_F$.

\paragraph{Data configurations.} We test four regimes: (a) Gaussian i.i.d., varying $n$ and $p$; (b) Student-$t_3$ (heavy-tailed), varying $n$; (c) prescribing a range of condition numbers $\kappa(\mathbf{X})\in[10,10^{14}]$; (d) near-singular data with smallest singular value $\sigma_{\min}\in[10^{-12},1]$.

\paragraph{Conformal experiments.} Calibration uses $m=600$ independent trajectories drawn from a $p=5$ multivariate distribution with Toeplitz covariance (entry $(i,j)$: $0.5^{|i-j|}$). Test coverage is estimated from 1200 fresh trajectories. The shift experiment varies the mean offset $c\in\{0,10^3,10^6,10^9,10^{12}\}$ on a $p=4$ identity-covariance distribution and evaluates coverage and interval width at $t=150$.

Results

Runtime

Figure (ref) shows wall-clock time versus $n$ for $p=10$ and $p=50$. Gram is the fastest batch method, consistently beating numpy.cov by a factor of $1.3$--$1.6\times$ due to the avoided $n\times p$ centering write. Welford is slowest by 50--80$\times$ in pure-Python form because the inner loop invokes numpy.outer once per row, incurring $O(n)$ Python-level calls; a compiled implementation would close this to $\approx2\times$ (the FLOP ratio from Table (ref)). CGL (recursive, block size 64) sits between the two.

figure[figure omitted — 503 chars of source]

Figure (ref) shows runtime versus dimension at fixed $n=4{,}000$. For large $p$ all batch methods are dominated by the $O(np^2)$ matrix multiply and their curves converge; Gram retains a small constant-factor advantage from avoiding the centred copy.

figure[figure omitted — 326 chars of source]

Figure (ref) shows the speed ratio of each method relative to Gram.

figure[figure omitted — 344 chars of source]

Numerical Accuracy: Gaussian Data

Figure (ref) shows accuracy on Gaussian i.i.d.\ data. All methods agree with numpy.cov to within $10^{-13}$ in both metrics, consistent with Propositions (ref)--(ref).

figure[figure omitted — 347 chars of source]

Heavy-Tailed and Ill-Conditioned Data

Figure (ref) tests Student-$t_3$ data. Errors remain at floating-point noise for all methods; heavy tails do not affect the relative comparison because all algorithms process the same finite-precision data.

figure[figure omitted — 353 chars of source]

Figure (ref) sweeps the condition number of $\mathbf{X}$. All methods degrade once $\kappa\gtrsim 10^7$, as predicted by standard floating-point theory; Welford and CGL are modestly more robust in the range $\kappa\in[10^6,10^{12}]$.

figure[figure omitted — 352 chars of source]

Catastrophic Cancellation Under Large Shift

Figure (ref) shifts all observations by a constant $c$ and measures error against the unshifted (true) covariance. Gram error grows as $c^2\varepsilon_{\mathrm{mach}}$ (Proposition (ref)), losing $\approx 9$--$10$ decimal digits by $c=10^{12}$. Welford maintains full double-precision accuracy throughout. CGL loses moderate accuracy, reflecting the inter-block cancellation in the merge formula.

figure[figure omitted — 345 chars of source]

Online Fidelity

Figure (ref) tracks $\|\widehat{\bm{\Sigma}}_t^{\mathcal{A}} - \widehat{\bm{\Sigma}}_t^{\mathrm{batch}}\|_{\max}$ as $t$ grows on a zero-mean stream. All methods converge to floating-point noise by $t\approx 100$; the early fluctuations are consistent with the $1/\sqrt{t}$ rate of the estimation error.

figure[figure omitted — 263 chars of source]

Conformal Prediction Results

\paragraph{Coverage and width under well-conditioned data.} Figure (ref) (left) shows empirical coverage versus $t$ for all three algorithms at nominal level $1-\alpha = 95\%$. All algorithms achieve the nominal level (dashed line) at every $t\ge 10$, confirming Theorem (ref). Coverage slightly exceeds 95% for small $t$ because the conformal quantile is conservative for small calibration sets. Figure (ref) (right) shows interval width: all three methods produce intervals of the same order, narrowing as $t$ grows. Gram produces marginally narrower intervals for well-conditioned data because its lower variance translates to tighter calibration scores.

figure[figure omitted — 452 chars of source]

\paragraph{Coverage under large mean shift.} Figure (ref) tests conformal coverage when calibration and test data share the same shift $c$ (left bars) for entry $(1,1)$ (the variance). All three algorithms maintain coverage because the shift is the same in calibration and test sets, so the nonconformity scores are exchangeable. However, Gram's interval widths (right panel) grow dramatically with $c$, reflecting the $O(c^2\varepsilon_{\mathrm{mach}})$ error term inflating the calibration scores. Welford and CGL maintain narrow intervals throughout.

figure[figure omitted — 546 chars of source]

Applications

\paragraph{Federated / privacy-restricted learning.} The Gram sufficient statistics $(\mathbf{G}_t,\mathbf{s}_t,t)$ can be computed locally at each node and aggregated without sharing raw observations. For privacy-sensitive settings where inter-node differences are large, the CGL protocol with block merging provides both the parallelism advantage and the numerical stability of Welford.

\paragraph{Sandwich covariance for M-estimators.} Let $\mathbf{g}_i\in\mathbb{R}^p$ be the score vector for observation $i$. The heteroskedasticity-consistent sandwich covariance white1980,newey1987 is $\hat\Omega = n/(n-1)\cdot (n\mathbf{G} - \mathbf{s}\mathbf{s}^\top)/n^2$ where $\mathbf{G} = \sum_i\mathbf{g}_i\mathbf{g}_i^\top$ and $\mathbf{s} = \sum_i\mathbf{g}_i$. This is precisely the Gram formula applied to the score matrix, admitting a streaming update as each observation is processed.

\paragraph{Panel / fixed-effects data.} For panel unit $i$ observed at $T$ periods, the within-unit covariance is $\hat\bm{\Sigma}_i = (\mathbf{X}_i^\top\mathbf{X}_i - T^{-1}\mathbf{s}_i\mathbf{s}_i^\top)/(T-1)$. The streaming formulation processes units sequentially without forming the full $NT\times p$ matrix.

\paragraph{Conformal uncertainty in online inference.} The conformal intervals of Section (ref) provide rigorous uncertainty quantification for covariance-based online learning algorithms (e.g., online PCA, online Mahalanobis distance) at every step of the stream, not just asymptotically.

Practitioner Decision Guide

table[table omitted — 752 chars of source]

Use the Gram algorithm when (a) data are zero-mean or pre-centred, (b) BLAS is well-tuned, or (c) only sufficient statistics can be stored. Use Welford when numerical stability under unknown shifts matters or when simplicity of implementation is paramount. Use CGL with large block size when data are distributed across nodes or when parallel computation is available. Combine any algorithm with the conformal protocol of Section (ref) for principled uncertainty quantification.

Conclusion

We have given a unified treatment of three streaming covariance algorithms---Gram, Welford, and Chan--Golub--LeVeque---covering algebraic equivalence, floating-point error analysis, computational cost, and a new conformal prediction framework. The key empirical findings are: (i) Gram is fastest for batch computation with BLAS, at a factor of $1.4$--$1.6\times$ over numpy.cov; (ii) Welford is the uniquely stable choice under large data shifts, maintaining double-precision accuracy where Gram loses up to 9 decimal digits; (iii) conformal intervals achieve the nominal 95% coverage for all three algorithms on well-conditioned data, but Gram's interval widths inflate catastrophically under large shifts while Welford's remain tight. Together, these results offer practitioners a clear basis for choosing among the three algorithms.

Additional Acknowledgements

The author thanks the numerical analysis literature on which this work builds, particularly higham2002 and chan1979.

thebibliography{99} \bibitem[Angelopoulos & Bates(2023)]{angelopoulos2023} Angelopoulos, A. N. and Bates, S. (2023). Conformal prediction: A gentle introduction. Foundations and Trends in Machine Learning, 16(4):494--591. \bibitem[Chan, Golub & LeVeque(1979)]{chan1979} Chan, T. F., Golub, G. H., and LeVeque, R. J. (1979). Updating formulae and a pairwise algorithm for computing sample variances. Technical Report STAN-CS-79-773, Stanford University. \bibitem[Golub & Van Loan(2013)]{golub2013} Golub, G. H. and Van Loan, C. F. (2013). Matrix Computations, 4th ed. Johns Hopkins University Press. \bibitem[Higham(2002)]{higham2002} Higham, N. J. (2002). Accuracy and Stability of Numerical Algorithms, 2nd ed. SIAM. \bibitem[Lehmann & Casella(1998)]{lehmann1998} Lehmann, E. L. and Casella, G. (1998). Theory of Point Estimation, 2nd ed. Springer. \bibitem[Newey & West(1987)]{newey1987} Newey, W. K. and West, K. D. (1987). A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix. Econometrica, 55(3):703--708. \bibitem[Papadopoulos et al.(2002)]{papadopoulos2002} Papadopoulos, H., Proedrou, K., Vovk, V., and Gammerman, A. (2002). Inductive confidence machines for regression. In \emph{Proc.\ ECML}, pp. 345--356. \bibitem[Reichel(2025)]{reichel2025bariance} Reichel, F. (2025). High-Performance Variance-–Covariance Matrix Construction Using an Uncentered Gram Formulation, Forthcoming in \emph{European Journal of Mathematics and Statistics (EJ-MATH)}. \bibitem[Vovk, Gammerman & Shafer(2005)]{vovk2005} Vovk, V., Gammerman, A., and Shafer, G. (2005). \emph{Algorithmic Learning in a Random World}. Springer. \bibitem[Welford(1962)]{welford1962} Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. \emph{Technometrics}, 4(3):419--420. \bibitem[White(1980)]{white1980} White, H. (1980). A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity. \emph{Econometrica}, 48(4):817--838.

Ommited Proofs

Proof of Theorem (ref): Gram Identity

proofExpand the $(k,l)$ entry of the left side of (ref) directly: \begin{align*} \sum_{i=1}^t (x_{ik}-\bar x_k)(x_{il}-\bar x_l) &= \sum_{i=1}^t x_{ik}x_{il} \;-\; \bar x_k\sum_{i=1}^t x_{il} \;-\; \bar x_l\sum_{i=1}^t x_{ik} \;+\; t\bar x_k\bar x_l\\ &= G_{kl} \;-\; \bar x_k s_l \;-\; \bar x_l s_k \;+\; t\bar x_k\bar x_l\\ &= G_{kl} \;-\; \frac{s_k s_l}{t} \;-\; \frac{s_l s_k}{t} \;+\; \frac{s_ks_l}{t}\\ &= G_{kl} \;-\; \frac{s_k s_l}{t}, \end{align*} where we used $\bar x_k = s_k/t$. Dividing by $t-1$ and multiplying numerator and denominator by $t$ gives \[ \frac{G_{kl} - s_ks_l/t}{t-1} = \frac{tG_{kl}-s_ks_l}{t(t-1)}, \] which is the $(k,l)$ entry of $(t\mathbf{G}_t - \mathbf{s}_t\mathbf{s}_t^\top)/[t(t-1)]$. Since this holds for every $(k,l)$, the matrix identity follows. \qquad\qquad$\square$

Proof of Theorem (ref): Welford Invariant

proofWe proceed by induction on $t$. \paragraph{Base case ($t=1$).} At $t=1$: $\bm{\mu}_1 = \mathbf{x}_1$, $\bm{\Delta} = \mathbf{x}_1 - \mathbf{0} = \mathbf{x}_1$, and $\mathbf{x}_1 - \bm{\mu}_1 = \mathbf{0}$, so $\mathbf{M}_1 = \mathbf{0}$. Thus, the claimed sum $\sum_{i=1}^1(\mathbf{x}_i-\bm{\mu}_1)(\mathbf{x}_i-\bm{\mu}_1)^\top = \mathbf{0}$. \paragraph{Inductive step.} Assume $\mathbf{M}_{t-1} = \sum_{i=1}^{t-1}(\mathbf{x}_i-\bm{\mu}_{t-1})(\mathbf{x}_i-\bm{\mu}_{t-1})^\top$. At step $t$, let $\bm{\Delta}_t = \mathbf{x}_t - \bm{\mu}_{t-1}$ and $\bm{\mu}_t = \bm{\mu}_{t-1} + \bm{\Delta}_t/t$. Then $\mathbf{x}_t - \bm{\mu}_t = \bm{\Delta}_t - \bm{\Delta}_t/t = (t-1)\bm{\Delta}_t/t$. The update is $\mathbf{M}_t = \mathbf{M}_{t-1} + \bm{\Delta}_t(\mathbf{x}_t-\bm{\mu}_t)^\top$. We need to show $\mathbf{M}_t = \sum_{i=1}^t(\mathbf{x}_i-\bm{\mu}_t)(\mathbf{x}_i-\bm{\mu}_t)^\top$. Write $\mathbf{x}_i - \bm{\mu}_t = (\mathbf{x}_i - \bm{\mu}_{t-1}) - (\bm{\mu}_t - \bm{\mu}_{t-1})$ $= (\mathbf{x}_i - \bm{\mu}_{t-1}) - \bm{\Delta}_t/t$ for each $i$. Then \begin{align*} \sum_{i=1}^t(\mathbf{x}_i-\bm{\mu}_t)(\mathbf{x}_i-\bm{\mu}_t)^\top &= \sum_{i=1}^{t-1}(\mathbf{x}_i-\bm{\mu}_t)(\mathbf{x}_i-\bm{\mu}_t)^\top + (\mathbf{x}_t - \bm{\mu}_t)(\mathbf{x}_t-\bm{\mu}_t)^\top \\ &= \sum_{i=1}^{t-1}\!\bigl[(\mathbf{x}_i-\bm{\mu}_{t-1}) - \tfrac{\bm{\Delta}_t}{t}\bigr] \bigl[(\mathbf{x}_i-\bm{\mu}_{t-1}) - \tfrac{\bm{\Delta}_t}{t}\bigr]^\top + \tfrac{(t-1)^2}{t^2}\bm{\Delta}_t\bm{\Delta}_t^\top. \end{align*} Expanding the sum and using $\sum_{i=1}^{t-1}(\mathbf{x}_i-\bm{\mu}_{t-1}) = \mathbf{0}$: \begin{align*} &= \sum_{i=1}^{t-1}(\mathbf{x}_i-\bm{\mu}_{t-1})(\mathbf{x}_i-\bm{\mu}_{t-1})^\top + \frac{t-1}{t^2}\bm{\Delta}_t\bm{\Delta}_t^\top + \frac{(t-1)^2}{t^2}\bm{\Delta}_t\bm{\Delta}_t^\top \\ &= \mathbf{M}_{t-1} + \frac{(t-1)}{t^2}\bigl[1 + (t-1)\bigr]\bm{\Delta}_t\bm{\Delta}_t^\top \\ &= \mathbf{M}_{t-1} + \frac{t-1}{t}\bm{\Delta}_t\bm{\Delta}_t^\top \\ &= \mathbf{M}_{t-1} + \bm{\Delta}_t\bigl(\tfrac{t-1}{t}\bm{\Delta}_t\bigr)^\top = \mathbf{M}_{t-1} + \bm{\Delta}_t(\mathbf{x}_t-\bm{\mu}_t)^\top = \mathbf{M}_t, \end{align*} completing the induction. \qquad\qquad$\square$

Proof of Theorem (ref): CGL Correctness

proofWrite $\bm{\mu}_{AB} = (n_A\bm{\mu}_A + n_B\bm{\mu}_B)/n_{AB}$. For $i\in A$: $\mathbf{x}_i - \bm{\mu}_{AB} = (\mathbf{x}_i - \bm{\mu}_A) + (\bm{\mu}_A - \bm{\mu}_{AB}) = (\mathbf{x}_i-\bm{\mu}_A) - n_B\bm{\Delta}/n_{AB}$. Summing outer products over $A$ and using $\sum_{i\in A}(\mathbf{x}_i-\bm{\mu}_A)=\mathbf{0}$: \[ \sum_{i\in A}(\mathbf{x}_i-\bm{\mu}_{AB})(\mathbf{x}_i-\bm{\mu}_{AB})^\top = \mathbf{M}_A + \frac{n_An_B^2}{n_{AB}^2}\bm{\Delta}\bm{\Delta}^\top. \] Similarly for $B$ (with $\bm{\mu}_B - \bm{\mu}_{AB} = n_A\bm{\Delta}/n_{AB}$): \[ \sum_{i\in B}(\mathbf{x}_i-\bm{\mu}_{AB})(\mathbf{x}_i-\bm{\mu}_{AB})^\top = \mathbf{M}_B + \frac{n_B n_A^2}{n_{AB}^2}\bm{\Delta}\bm{\Delta}^\top. \] Adding: \[ \mathbf{M}_{A\cup B} = \mathbf{M}_A + \mathbf{M}_B + \frac{n_An_B(n_B + n_A)}{n_{AB}^2}\bm{\Delta}\bm{\Delta}^\top = \mathbf{M}_A + \mathbf{M}_B + \frac{n_An_B}{n_{AB}}\bm{\Delta}\bm{\Delta}^\top. \qquad\square \]

Proofs of Floating-Point Bounds (Propositions (ref)--(ref))

We use the standard model of floating-point arithmetic higham2002: for any operation $\circ\in\{+,-,\times,\div\}$, $\mathrm{fl}(a\circ b) = (a\circ b)(1+\delta)$ with $|\delta|\le\varepsilon_{\mathrm{mach}}$. Sequential summation of $n$ terms bounded by $M$ satisfies $|\hat S_n - S_n| \le (n-1)\varepsilon_{\mathrm{mach}}\cdot nM + O(\varepsilon_{\mathrm{mach}}^2)$ higham2002.

proof[Proof of Proposition (ref)] The $(k,l)$ entry of $\hat\mathbf{G}_t$ is computed as $\hat G_{kl} = \sum_{i=1}^t x_{ik}x_{il}$ in floating point. By the summation error bound each term $x_{ik}x_{il}$ is bounded by $X^2$, giving $|\hat G_{kl} - G_{kl}| \le (t-1)\varepsilon_{\mathrm{mach}}\cdot tX^2 + O(\varepsilon_{\mathrm{mach}}^2)$. The outer product $\hat s_k\hat s_l$ contributes an additional rounding at scale $|\bar x_k||\bar x_l|t^2$. Forming $(t\hat G_{kl} - \hat s_k\hat s_l)/[t(t-1)]$: \begin{align*} \bigl|\hat\Sigma_{kl}^{\rm Gram} - \Sigma_{kl}\bigr| &\le \frac{t\,|\hat G_{kl} - G_{kl}| + |\hat s_k\hat s_l - s_ks_l|}{t(t-1)} + O(\varepsilon_{\mathrm{mach}}^2) \\ &\le \frac{(t-1)\varepsilon_{\mathrm{mach}}\,tX^2 + |\bar x_k||\bar x_l|t^2\varepsilon_{\mathrm{mach}}}{t(t-1)} + O(\varepsilon_{\mathrm{mach}}^2) \\ &\lesssim X^2\varepsilon_{\mathrm{mach}} + \frac{\bar x_k\bar x_l}{t-1}\varepsilon_{\mathrm{mach}}. \qquad\square \end{align*}
proof[Proof of Proposition (ref)] At each step $t$ the Welford algorithm computes $\bm{\Delta}_t = \mathbf{x}_t - \hat\bm{\mu}_{t-1}$ and $\mathbf{x}_t - \hat\bm{\mu}_t$ as residuals. Each outer product $\hat\bm{\Delta}_t(\mathbf{x}_t-\hat\bm{\mu}_t)^\top$ has entries of magnitude $O(\sigma_k\sigma_l)$ on average (in expectation over the trajectory). Sequential accumulation over $t-1$ steps gives \[ |\hat\Sigma_{kl}^{\rm Welf} - \Sigma_{kl}| \le (t-1)\varepsilon_{\mathrm{mach}}\,\sigma_k\sigma_l + O(\varepsilon_{\mathrm{mach}}^2), \] independent of $\bar x_k$ or $\bar x_l$. See chan1979, Theorem 3.1, for a detailed treatment. \qquad$\square$
proof[Proof of Proposition (ref)] A single merge call introduces rounding error $|\delta[\mathbf{M}_{AB}]_{kl}|\le 3\varepsilon_{\mathrm{mach}}\cdot(n_An_B/n_{AB})|\Delta_k||\Delta_l|+O(\varepsilon_{\mathrm{mach}}^2)$ in the correction term. For a balanced binary tree of depth $d=\log_2 t$, there are $t-1$ total merges. At level $j$ (counting from leaves), there are $t/2^j$ merges each with block sizes $\approx 2^j$, contributing $O(\varepsilon_{\mathrm{mach}}\sigma_k\sigma_l)$ each. Summing over $d=\log_2 t$ levels: \[ |\hat\Sigma_{kl}^{\rm CGL} - \Sigma_{kl}| = O(\sigma_k\sigma_l\,\varepsilon_{\mathrm{mach}}\log_2 t). \qquad\square \]
proof[Proof of Proposition (ref)] Suppose $\mathbf{x}_i = \bm{\mu} + \mathbf{z}_i$ with $\mathbb{E}[\mathbf{z}_i]=\mathbf{0}$ and $\mathbb{E}[\mathbf{z}_i\mathbf{z}_i^\top]=\bm{\Sigma}$. Then $G_{kl} = \mu_k\mu_l t + \sum_i(z_{ik}\mu_l + z_{il}\mu_k + z_{ik}z_{il})$ and $s_k s_l/t = \mu_k\mu_l t + \text{(lower order)}$. The dominant terms in $tG_{kl}$ and $s_ks_l$ are both $O(\mu_k\mu_l t^2)$, and their difference is $O(t\Sigma_{kl})$. In floating point, $\hat G_{kl}$ has rounding error $O(tX^2\varepsilon_{\mathrm{mach}})$ where $X\approx |\mu_k|+\sigma_k$. When $|\mu_k|\gg\sigma_k$, $X\approx|\mu_k|$, and the error in $\widehat{\bm{\Sigma}}_{kl}^{\rm Gram}$ is dominated by $t|\mu_k|^2\varepsilon_{\mathrm{mach}}/[t(t-1)] = |\mu_k|^2\varepsilon_{\mathrm{mach}}/(t-1) \approx \mu_k^2\varepsilon_{\mathrm{mach}}$, which sums to $O(pc^2\varepsilon_{\mathrm{mach}})$ over the $p$ diagonal entries, giving $\left\lVert\widehat{\bm{\Sigma}}^{\rm Gram}-\bm{\Sigma}\right\rVert_F\gtrsim pc^2\varepsilon_{\mathrm{mach}}$. For Welford, $\bm{\Delta}_t = \mathbf{z}_t + (\bm{\mu} - \hat\bm{\mu}_{t-1})$ is $O(\sigma)$ once the running mean has converged (which happens geometrically fast). The outer product $\bm{\Delta}_t(\mathbf{x}_t-\hat\bm{\mu}_t)^\top$ is then $O(\sigma^2)$ regardless of $c$, giving $\left\lVert\widehat{\bm{\Sigma}}^{\rm Welf}-\bm{\Sigma}\right\rVert_F=O(p\sigma^2\varepsilon_{\mathrm{mach}})$. $\square$

Proof of Proposition (ref): Cancellation Bound

proofWrite each observation as $\mathbf{x}_i=\bm{\mu}+\mathbf{z}_i$, where the centred component satisfies $\mathbb{E}[\mathbf{z}_i]=\mathbf{0}$ and $\mathbb{E}[\mathbf{z}_i\mathbf{z}_i^\top]=\bm{\Sigma}$. For a fixed entry $(k,l)$, the Gram statistics are \[ G_{kl} = \sum_{i=1}^t x_{ik}x_{il} = t\mu_k\mu_l + \mu_k\sum_{i=1}^t z_{il} + \mu_l\sum_{i=1}^t z_{ik} + \sum_{i=1}^t z_{ik}z_{il}, \] and \[ s_k s_l = \left(t\mu_k+\sum_{i=1}^t z_{ik}\right) \left(t\mu_l+\sum_{i=1}^t z_{il}\right). \] Hence the two quantities entering the Gram numerator, $tG_{kl}$ and $s_k s_l$, both contain the leading term $t^2\mu_k\mu_l$. In exact arithmetic these leading terms cancel, leaving a centred quantity of order $t\Sigma_{kl}$. In floating-point arithmetic, however, the products and sums are formed at the raw data scale $|\mu_k|+\sigma_k$. Thus the rounding error in the Gram numerator contains a term of size \[ O\!\left(t^2|\mu_k\mu_l|\varepsilon_{\mathrm{mach}}\right), \] and division by $t(t-1)$ gives the entry-wise contribution \[ \bigl|\widehat{\bm{\Sigma}}_{kl,t}^{\mathrm{Gram}}-\Sigma_{kl,t}\bigr| \gtrsim |\mu_k\mu_l|\varepsilon_{\mathrm{mach}}. \] Summing these contributions over the diagonal entries gives \[ \left\lVert\widehat{\bm{\Sigma}}_t^{\mathrm{Gram}}-\bm{\Sigma}_t\right\rVert_F \gtrsim \sum_{k=1}^p \mu_k^2\varepsilon_{\mathrm{mach}}. \] Since $\sum_{k=1}^p\mu_k^2=\|\bm{\mu}\|_2^2=c^2$, this is of order $c^2\varepsilon_{\mathrm{mach}}$; in the common dense-shift case, where the mean contribution is spread across the $p$ coordinates at comparable scale, the Frobenius accumulation is written as \[ \left\lVert\widehat{\bm{\Sigma}}_t^{\mathrm{Gram}}-\bm{\Sigma}_t\right\rVert_F \gtrsim pc^2\varepsilon_{\mathrm{mach}}. \] For Welford, the update is based on residuals \[ \bm{\Delta}_t=\mathbf{x}_t-\bm{\mu}_{t-1}, \qquad \mathbf{x}_t-\bm{\mu}_t. \] The common shift $\bm{\mu}$ cancels in these differences. Consequently, once the running mean has reached the scale of the sample mean, both residual factors are governed by the centred variables $\mathbf{z}_i$, not by the absolute location $\bm{\mu}$. Each outer-product correction therefore has entries of order $\sigma_k\sigma_l$, and the floating-point error accumulates at covariance scale rather than raw-data scale: \[ \bigl|\widehat{\bm{\Sigma}}_{kl,t}^{\mathrm{Welf}}-\Sigma_{kl,t}\bigr| = O(\sigma_k\sigma_l\varepsilon_{\mathrm{mach}}). \] Taking the Frobenius norm over the $p\times p$ matrix yields \[ \left\lVert\widehat{\bm{\Sigma}}_t^{\mathrm{Welf}}-\bm{\Sigma}_t\right\rVert_F = O(p\sigma^2\varepsilon_{\mathrm{mach}}), \] which does not depend on $c$.

Proof of Theorem (ref): Conformal Coverage

proofLet $Z_1,\ldots,Z_m,Z_{m+1}$ be i.i.d.\ random variables, where $Z_j = |\widehat{\bm{\Sigma}}_t^{(j)}{}_{kl} - \Sigma_{kl}|$ for $j\le m$ (calibration) and $Z_{m+1}$ is the test score. By exchangeability, for any fixed threshold $q$, $\Pr(Z_{m+1} > q) = \Pr(Z_1 > q)$. The conformal quantile $\hat q_\alpha^+ = \mathrm{Quantile}(\{Z_j\}_{j=1}^m;\, \lceil(m+1)(1-\alpha)\rceil/m)$ is defined so that $\hat q_\alpha^+ \ge Z_{(k^*)}$ where $k^* = \lceil(m+1)(1-\alpha)\rceil$ is the $k^*$-th order statistic. By the standard conformal coverage argument vovk2005, \[ \Pr(Z_{m+1} \le \hat q_\alpha^+) \ge 1 - \alpha. \] Since $Z_{m+1} \le \hat q_\alpha^+$ is equivalent to $|\widehat{\bm{\Sigma}}_t^{(m+1)}{}_{kl} - \Sigma_{kl}|\le \hat q_\alpha^+$, which is the event that $\Sigma_{kl}\in\hat C_\alpha(t)$, the coverage guarantee follows. \qquad\qquad$\square$

Bariance Scalar Identity

definition[Bariance reichel2025bariance] For $n\ge 2$ and $x_1,\ldots,x_n\in\mathbb{R}$, \[ \mathrm{Bar}(x_1,\ldots,x_n) = \frac{1}{2n(n-1)}\sum_{i\ne j}(x_i-x_j)^2. \]
proposition$\mathrm{Bar}(x) = (nS_{xx}-S_x^2)/[n(n-1)]$, where $S_x = \sum_i x_i$ and $S_{xx}=\sum_i x_i^2$. Moreover, $\mathrm{Bar}(x) = \hat\sigma^2 = \frac{1}{n-1}\sum_i(x_i-\bar x)^2$.
proofExpand $(x_i-x_j)^2 = x_i^2 - 2x_ix_j + x_j^2$ and sum over $i\ne j$. Using $\sum_{i\ne j}x_i^2 = (n-1)S_{xx}$ and $\sum_{i\ne j}x_ix_j = S_x^2 - S_{xx}$: \[ \sum_{i\ne j}(x_i-x_j)^2 = 2(n-1)S_{xx} - 2(S_x^2-S_{xx}) = 2nS_{xx}-2S_x^2. \] Divide by $2n(n-1)$. The equality with $\hat\sigma^2$ follows from $\sum_i(x_i-\bar x)^2 = S_{xx} - S_x^2/n$ and standard algebra.