Skip to content
Kittycat.tech logo

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

Just click the copy button in the top right corner of each code block!

Summary Overview ​

#FormulaExample
1Mean[3,6,12]→7
2Median[3,1,4,1,5]→3
3Mode[1,2,2,3,3,3]→3
4Range[4,…,42]→38
5Varianceσ2=4, s2≈4.5714
6Standard Deviationσ=2, s≈2.1381
7z-scorex=85,μ=70,σ=10→1.5
8Quartiles and Interquartile Range[1,…,8]→IQR=3.5
9Covariance and CorrelationCov=1.5, r≈0.7746

1. Mean ​

Mean

Formula:

x¯=∑i=1nxin

Python also has statistics.mean() built in.

Where it's used: describing the centre of a dataset.

Reusable Python code snippet for Mean formula

markdown
$$
\bar{x} = \frac{\sum_{i=1}^{n} x_i}{n}
$$
python
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]))
rust
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:

x~={x(n+12)if n is odd12(x(n2)+x(n2+1))if n is even

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.

markdown
$$
\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}
$$
python
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.5
rust
fn 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:

Mode=arg⁡maxxcount(x)

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.

markdown
$$
\operatorname{Mode} = \underset{x}{\arg\max} \; \operatorname{count}(x)
$$
python
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]))  # 3
rust
use 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:

Range=xmax−xmin

Where it's used: a quick first look at how spread out the data is.

markdown
$$
\text{Range} = x_{\max} - x_{\min}
$$
python
def value_range(values: list[float]) -> float:
    return max(values) - min(values)

print(value_range([4, 8, 15, 16, 23, 42]))  # 38
rust
fn 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:

σ2=1N∑i=1N(xi−μ)2s2=1n−1∑i=1n(xi−x¯)2

Use the population version σ2 for a whole population and the sample version s2 for a sample.

Where it's used: measuring how spread out the data is.

markdown
$$
\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
$$
python
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.5714
rust
fn 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:

σ=1N∑i=1N(xi−μ)2s=1n−1∑i=1n(xi−x¯)2

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.

markdown
$$
\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}
$$
python
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.1381
rust
fn 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:

z=x−μσ

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.

markdown
$$
z = \frac{x - \mu}{\sigma}
$$
python
def z_score(x: float, mu: float, sigma: float) -> float:
    return (x - mu) / sigma

print(z_score(85, 70, 10))  # 1.5
rust
fn 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:

IQR=Q3−Q1

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.

markdown
$$
\text{IQR} = Q_3 - Q_1
$$
python
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.5
rust
fn 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:

Cov(X,Y)=1n−1∑i=1n(xi−x¯)(yi−y¯)r=Cov(X,Y)sXsY

The correlation r is always between −1 and 1. The covariance of a variable with itself is its variance.

Where it's used: measuring how two features move together, and choosing features for a model.

markdown
$$
\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}
$$
python
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.7746
rust
fn 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
}

✅Study notes based on Kittycat's insights from the best online courses at top universities