Descriptive Statistics Formulas in LaTeX, Python and Rust
✅ Copy-ready code for descriptive statistics formulas in LaTeX, Python and Rust. For each formula, you'll see how to write it in LaTeX and how to calculate it in code. 😻
Every snippet runs on its own with no extra libraries, and the expected output is written in the comments. Use the tabs to switch between LaTeX, Python and Rust. To run a Rust snippet, save it as main.rs and run rustc main.rs, or paste it into the Rust Playground.
📚 Math Formulas in Code series
- Part 1: Algebra Formulas: exponents, logarithms, quadratics, lines and sequences
- Part 2: Linear Algebra Formulas: vectors, matrices and a neural network layer
- Part 3: Descriptive Statistics Formulas (you are here): mean, median, spread and correlation
- Part 4: Inferential Statistics Formulas: tests, confidence intervals, probability and regression
- Part 5: Calculus Formulas: derivatives, integrals and numerical methods
Just click the copy button in the top right corner of each code block!
Summary Overview
| # | Formula | Example |
|---|---|---|
| 1 | Mean | |
| 2 | Median | |
| 3 | Mode | |
| 4 | Range | |
| 5 | Variance | |
| 6 | Standard Deviation | |
| 7 | z-score | |
| 8 | Quartiles and Interquartile Range | |
| 9 | Covariance and Correlation |
1. Mean
Mean
Formula:
Python also has statistics.mean() built in.
Where it's used: describing the centre of a dataset.
Reusable Python code snippet for Mean formula
$$
\bar{x} = \frac{\sum_{i=1}^{n} x_i}{n}
$$from typing import List
def mean(values: List[float]):
sum = 0.0
for value in values:
sum += value
return sum / len(values)
# should print 0.0
print(mean([-2, 2]))
# should print 7.0
print(mean([3, 6, 12]))fn mean(values: &[f64]) -> f64 {
values.iter().sum::<f64>() / values.len() as f64
}
fn main() {
println!("{}", mean(&[-2.0, 2.0])); // 0
println!("{}", mean(&[3.0, 6.0, 12.0])); // 7
}2. Median
Median
Formula:
Sort the data first. In Rust, decimals cannot use .sort() directly, so the code uses sort_by with partial_cmp.
Where it's used: describing the centre of skewed data, such as incomes or house prices.
$$
\tilde{x} = \begin{cases} x_{\left( \frac{n+1}{2} \right)} & \text{if } n \text{ is odd} \\ \frac{1}{2} \left( x_{\left( \frac{n}{2} \right)} + x_{\left( \frac{n}{2} + 1 \right)} \right) & \text{if } n \text{ is even} \end{cases}
$$def median(values: list[float]) -> float:
s = sorted(values)
n = len(s)
mid = n // 2
if n % 2 == 1:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
print(median([3, 1, 4, 1, 5])) # 3
print(median([1, 2, 3, 4])) # 2.5fn median(values: &[f64]) -> f64 {
let mut s = values.to_vec();
s.sort_by(|a, b| a.partial_cmp(b).unwrap());
let n = s.len();
let mid = n / 2;
if n % 2 == 1 {
s[mid]
} else {
(s[mid - 1] + s[mid]) / 2.0
}
}
fn main() {
println!("{}", median(&[3.0, 1.0, 4.0, 1.0, 5.0])); // 3
println!("{}", median(&[1.0, 2.0, 3.0, 4.0])); // 2.5
}3. Mode
Mode
Formula:
If two values appear equally often, these functions return only one of them.
Where it's used: the most common category, such as the most popular product.
$$
\operatorname{Mode} = \underset{x}{\arg\max} \; \operatorname{count}(x)
$$def mode(values: list[int]) -> int:
counts = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
return max(counts, key=counts.get)
print(mode([1, 2, 2, 3, 3, 3])) # 3use std::collections::HashMap;
fn mode(values: &[i64]) -> i64 {
let mut counts = HashMap::new();
for &v in values {
*counts.entry(v).or_insert(0) += 1;
}
counts.into_iter().max_by_key(|&(_, c)| c).map(|(v, _)| v).unwrap()
}
fn main() {
println!("{}", mode(&[1, 2, 2, 3, 3, 3])); // 3
}4. Range
Range
Formula:
Where it's used: a quick first look at how spread out the data is.
$$
\text{Range} = x_{\max} - x_{\min}
$$def value_range(values: list[float]) -> float:
return max(values) - min(values)
print(value_range([4, 8, 15, 16, 23, 42])) # 38fn value_range(values: &[f64]) -> f64 {
let max = values.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let min = values.iter().cloned().fold(f64::INFINITY, f64::min);
max - min
}
fn main() {
println!("{}", value_range(&[4.0, 8.0, 15.0, 16.0, 23.0, 42.0])); // 38
}5. Variance
Variance
Formula:
Use the population version
Where it's used: measuring how spread out the data is.
$$
\sigma^2 = \frac{1}{N} \sum_{i=1}^{N} (x_i - \mu)^2 \qquad s^2 = \frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})^2
$$def variance(values: list[float], sample: bool = True) -> float:
n = len(values)
m = sum(values) / n
squares = sum((x - m) ** 2 for x in values)
return squares / (n - 1) if sample else squares / n
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(variance(data, sample=False)) # 4.0
print(round(variance(data), 4)) # 4.5714fn variance(values: &[f64], sample: bool) -> f64 {
let n = values.len() as f64;
let m = values.iter().sum::<f64>() / n;
let squares: f64 = values.iter().map(|x| (x - m).powi(2)).sum();
if sample { squares / (n - 1.0) } else { squares / n }
}
fn main() {
let data = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
println!("{}", variance(&data, false)); // 4
println!("{:.4}", variance(&data, true)); // 4.5714
}6. Standard Deviation
Standard Deviation
Formula:
The standard deviation is the square root of the variance, so it has the same units as the data.
Where it's used: describing spread in the original units, and scaling features.
$$
\sigma = \sqrt{\frac{1}{N} \sum_{i=1}^{N} (x_i - \mu)^2} \qquad s = \sqrt{\frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})^2}
$$import math
def std_dev(values: list[float], sample: bool = True) -> float:
n = len(values)
m = sum(values) / n
squares = sum((x - m) ** 2 for x in values)
return math.sqrt(squares / (n - 1 if sample else n))
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(std_dev(data, sample=False)) # 2.0
print(round(std_dev(data), 4)) # 2.1381fn std_dev(values: &[f64], sample: bool) -> f64 {
let n = values.len() as f64;
let m = values.iter().sum::<f64>() / n;
let squares: f64 = values.iter().map(|x| (x - m).powi(2)).sum();
let divisor = if sample { n - 1.0 } else { n };
(squares / divisor).sqrt()
}
fn main() {
let data = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
println!("{}", std_dev(&data, false)); // 2
println!("{:.4}", std_dev(&data, true)); // 2.1381
}7. z-score
z-score
Formula:
A z-score of 1.5 means the value is 1.5 standard deviations above the mean.
Where it's used: comparing values on different scales, and standardising features before training.
$$
z = \frac{x - \mu}{\sigma}
$$def z_score(x: float, mu: float, sigma: float) -> float:
return (x - mu) / sigma
print(z_score(85, 70, 10)) # 1.5fn z_score(x: f64, mu: f64, sigma: f64) -> f64 {
(x - mu) / sigma
}
fn main() {
println!("{}", z_score(85.0, 70.0, 10.0)); // 1.5
}8. Quartiles and Interquartile Range
Quartiles and Interquartile Range
Formula:
Tools calculate quartiles in slightly different ways. This code uses linear interpolation, the same method as NumPy's default.
Where it's used: box plots and finding outliers.
$$
\text{IQR} = Q_3 - Q_1
$$def quantile(values: list[float], p: float) -> float:
s = sorted(values)
pos = (len(s) - 1) * p # linear interpolation
lower = int(pos)
if lower + 1 < len(s):
return s[lower] + (pos - lower) * (s[lower + 1] - s[lower])
return s[lower]
data = [1, 2, 3, 4, 5, 6, 7, 8]
q1, q3 = quantile(data, 0.25), quantile(data, 0.75)
print(q1, q3, q3 - q1) # 2.75 6.25 3.5fn quantile(values: &[f64], p: f64) -> f64 {
let mut s = values.to_vec();
s.sort_by(|a, b| a.partial_cmp(b).unwrap());
let pos = (s.len() - 1) as f64 * p; // linear interpolation
let lower = pos.floor() as usize;
if lower + 1 < s.len() {
s[lower] + (pos - lower as f64) * (s[lower + 1] - s[lower])
} else {
s[lower]
}
}
fn main() {
let data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
let (q1, q3) = (quantile(&data, 0.25), quantile(&data, 0.75));
println!("{} {} {}", q1, q3, q3 - q1); // 2.75 6.25 3.5
}9. Covariance and Correlation
Covariance and Correlation
Formula:
The correlation
Where it's used: measuring how two features move together, and choosing features for a model.
$$
\operatorname{Cov}(X, Y) = \frac{1}{n - 1} \sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y}) \qquad r = \frac{\operatorname{Cov}(X, Y)}{s_X \, s_Y}
$$import math
def covariance(x: list[float], y: list[float]) -> float:
n = len(x)
mx, my = sum(x) / n, sum(y) / n
return sum((a - mx) * (b - my) for a, b in zip(x, y)) / (n - 1)
def correlation(x: list[float], y: list[float]) -> float:
return covariance(x, y) / math.sqrt(covariance(x, x) * covariance(y, y))
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 5]
print(covariance(x, y)) # 1.5
print(round(correlation(x, y), 4)) # 0.7746fn covariance(x: &[f64], y: &[f64]) -> f64 {
let n = x.len() as f64;
let mx = x.iter().sum::<f64>() / n;
let my = y.iter().sum::<f64>() / n;
x.iter().zip(y).map(|(a, b)| (a - mx) * (b - my)).sum::<f64>() / (n - 1.0)
}
fn correlation(x: &[f64], y: &[f64]) -> f64 {
covariance(x, y) / (covariance(x, x) * covariance(y, y)).sqrt()
}
fn main() {
let x = [1.0, 2.0, 3.0, 4.0, 5.0];
let y = [2.0, 4.0, 5.0, 4.0, 5.0];
println!("{}", covariance(&x, &y)); // 1.5
println!("{:.4}", correlation(&x, &y)); // 0.7746
}