Algorithm Search⌘K

Algorithmintro

Trimmed mean

Also called truncated mean.

The mean of the sample after removing a fixed fraction of the smallest and of the largest values. Its breakdown point tends to that fraction as the sample grows.

Time
Θ(n²) worstΘ(n) average · best
Space
Θ(n) extra
Where
g = the number of values cut from each end; n = the sample size
Properties
randomizedexact in exact arithmeticnot in placeofflinerandomized
Origin
John W. Tukey, Donald H. McLaughlin, 1963

The α\alpha-trimmed mean drops the g=⌊αn⌋g = \lfloor \alpha n \rfloor smallest and the gg largest values of a sample and averages the rest. It sits between the mean (g=0g = 0) and the median (gg as large as possible). With α\alpha between 0.1 and 0.25 it keeps most of the efficiency of the mean at the normal law and resists a fraction α\alpha of outliers. Two selections find the kept values without a sort, so the cost is expected Θ(n)\Theta(n).

In plain words

Judges score a performance. The organizers drop the highest score and the lowest score, then take the average of the others. One judge who gives an extreme score, by error or by bias, cannot change the result much. The trimmed mean is this rule with a fixed share of scores dropped at each end. To find the scores to keep, you do not need to put all of them in order. You only need to find the scores at the two cut points.

The problem

The input is a sample x1,…,xnx_1, \ldots, x_n of real numbers and a fraction 0≤α<1/20 \le \alpha < 1/2, or directly an integer g≥0g \ge 0 with n−2g≥1n - 2g \ge 1. Let x(1)≤⋯≤x(n)x_{(1)} \le \cdots \le x_{(n)} be the order statistics. The output is

xˉα=1n−2g∑i=g+1n−gx(i),g=⌊αn⌋.\bar x_\alpha = \frac{1}{n - 2g} \sum_{i = g+1}^{n-g} x_{(i)}, \qquad g = \lfloor \alpha n \rfloor.

The algorithm

SELECT(A,lo,hi,k)(A, lo, hi, k) is quickselect on A[lo…hi]A[lo \ldots hi] with a random pivot and a three-way partition. It rearranges the range so that A[k]A[k] holds the value of rank k−lok - lo in the range, with A[lo…k−1]≤A[k]≤A[k+1…hi]A[lo \ldots k-1] \le A[k] \le A[k+1 \ldots hi].

  1. TRIMMED-MEAN(x, α) ▷ x[0 .. n − 1], 0 ≤ α < 1/2
  2. 1n ← |x|, g ← ⌊α n⌋ (in exact arithmetic), A ← a copy of x
  3. 2if n − 2g < 1 then error
  4. 3SELECT(A, 0, n − 1, g) ▷ A[g] = x(g+1)
  5. 4SELECT(A, g, n − 1, n − g − 1) ▷ A[n − g − 1] = x(n−g)
  6. 5s ← A[g] + A[g + 1] + ... + A[n − g − 1]
  7. 6return s / (n − 2g)

Line L3 puts the gg smallest values in A[0…g−1]A[0 \ldots g-1]. Line L4 works only on the rest, A[g…n−1]A[g \ldots n-1], and puts the gg largest values at its right end. What is left in the middle is exactly the multiset of kept values, in some order. The order does not matter for a sum.

Example

Take x=(12,7,3,95,5,8,6,1,10,4)x = (12, 7, 3, 95, 5, 8, 6, 1, 10, 4) and α=0.2\alpha = 0.2. Then n=10n = 10 and g=2g = 2.

step content of AA (one possible order) what is fixed
L3, rank 2 in A[0..9]A[0..9] (3, 1, 4, 12, 7, 95, 5, 8, 6, 10) A[0..1]={1,3}A[0..1] = \{1, 3\}, A[2]=4A[2] = 4
L4, rank 7 in A[2..9]A[2..9] (3, 1, 4, 7, 5, 8, 6, 10, 12, 95) A[8..9]={12,95}A[8..9] = \{12, 95\}, A[7]=10A[7] = 10
L5 A[2..7]=(4,7,5,8,6,10)A[2..7] = (4, 7, 5, 8, 6, 10) sum 40

The result is 40/6=20/3≈6.66740/6 = 20/3 \approx 6.667. The sorted sample is (1,3,4,5,6,7,8,10,12,95)(1, 3, 4, 5, 6, 7, 8, 10, 12, 95), so the kept values are x(3),…,x(8)x_{(3)}, \ldots, x_{(8)}, as claimed. The mean of the sample is 15.115.1, pulled up by the value 95. The median is 6.56.5. The exact order inside each part depends on the random pivots.

Correctness

The key fact: after SELECT on a range with result position kk, the range is a permutation of its old content, and A[lo…k−1]≤A[k]≤A[k+1…hi]A[lo \ldots k-1] \le A[k] \le A[k+1 \ldots hi]. So if you sort each part, the concatenation is sorted. It follows that A[lo…k−1]A[lo \ldots k-1] holds the k−lok - lo smallest values of the range, as a multiset, even with ties. After L3, A[0…g−1]A[0 \ldots g-1] is {x(1),…,x(g)}\{x_{(1)}, \ldots, x_{(g)}\} and A[g…n−1]A[g \ldots n-1] is {x(g+1),…,x(n)}\{x_{(g+1)}, \ldots, x_{(n)}\}. L4 applies the same fact to this range and splits off its gg largest values. So A[g…n−g−1]A[g \ldots n-g-1] is {x(g+1),…,x(n−g)}\{x_{(g+1)}, \ldots, x_{(n-g)}\}. The proof, with the correctness of the three-way partition, is in proofs/correctness.md.

Proof: TRIMMED-MEAN returns the mean of the middle order statisticsfull

Let x(1)≤⋯≤x(n)x_{(1)} \le \cdots \le x_{(n)} be the sorted sample and g=⌊αn⌋g = \lfloor \alpha n \rfloor with n−2g≥1n - 2g \ge 1. For a list BB, write sort⁡(B)\operatorname{sort}(B) for its values in non-decreasing order, and { ⁣{B} ⁣}\{\!\{B\}\!\} for its multiset. The arithmetic is exact.

Lemma 1 (three-way partition). Let the loop of SELECT start a round on A[lo…hi]A[lo \ldots hi] with pivot value pp. When the inner loop stops, the range is a permutation of its old content, and with the final indices lt≤gtlt \le gt,

A[lo…lt−1]<p,A[lt…gt]=p,A[gt+1…hi]>p,A[lo \ldots lt-1] < p, \qquad A[lt \ldots gt] = p, \qquad A[gt+1 \ldots hi] > p,

and lt≤gtlt \le gt (the part equal to pp is not empty).

Proof. The loop keeps the invariant: A[lo…lt−1]<pA[lo \ldots lt-1] < p, A[lt…i−1]=pA[lt \ldots i-1] = p, A[gt+1…hi]>pA[gt+1 \ldots hi] > p, and A[i…gt]A[i \ldots gt] is not yet seen. At the start lt=i=lolt = i = lo and gt=higt = hi, and all three parts are empty. Each step looks at A[i]A[i]. If A[i]<pA[i] < p, the swap with A[lt]A[lt] moves an item equal to pp (or A[i]A[i] itself when lt=ilt = i) to position ii, and both indices grow. If A[i]>pA[i] > p, the swap puts it at gtgt, and gtgt shrinks. Otherwise ii grows. Each step changes the range only by a swap, and shrinks the unseen part by one. The loop ends when i=gt+1i = gt + 1, so the unseen part is empty. The pivot pp is a value of the range, so the middle part holds at least that item. □\square

Lemma 2 (SELECT). After SELECT(A,lo,hi,k)(A, lo, hi, k) with lo≤k≤hilo \le k \le hi, the range A[lo…hi]A[lo \ldots hi] is a permutation of its old content, the rest of AA is unchanged, and

A[lo…k−1]≤A[k]≤A[k+1…hi].A[lo \ldots k-1] \le A[k] \le A[k+1 \ldots hi].

Proof. Invariant of the outer loop: the current window [lo′,hi′][lo', hi'] contains kk, every item left of the window (inside the original range) is at most every item in the window, and every item right of the window is at least every item in the window. It holds at the start. After a round with k<ltk < lt, the new window [lo′,lt−1][lo', lt - 1] contains kk; the items in A[lt…hi′]A[lt \ldots hi'] are at least pp, and so at least every item of the new window (all <p< p). The case k>gtk > gt is symmetric. The window shrinks by at least one item per round (Lemma 1, the middle part is not empty), so the loop ends. It ends when the window has one item, or when lt≤k≤gtlt \le k \le gt. In the second case A[k]=pA[k] = p, all items of A[lo′…k−1]A[lo' \ldots k-1] are at most pp, and all of A[k+1…hi′]A[k+1 \ldots hi'] are at least pp. With the invariant this gives the claim. Only swaps inside the range change AA. □\square

Lemma 3 (split). Let B=A[lo…hi]B = A[lo \ldots hi] satisfy A[lo…k−1]≤A[k]≤A[k+1…hi]A[lo \ldots k-1] \le A[k] \le A[k+1 \ldots hi], and let j=k−loj = k - lo. Then { ⁣{A[lo…k−1]} ⁣}\{\!\{A[lo \ldots k-1]\}\!\} is the multiset of the first jj entries of sort⁡(B)\operatorname{sort}(B), A[k]A[k] is entry jj (from 0), and { ⁣{A[k+1…hi]} ⁣}\{\!\{A[k+1 \ldots hi]\}\!\} is the multiset of the rest.

Proof. Sort the left part and the right part separately. The list sort⁡(A[lo…k−1]), A[k], sort⁡(A[k+1…hi])\operatorname{sort}(A[lo \ldots k-1]),\ A[k],\ \operatorname{sort}(A[k+1 \ldots hi]) is non-decreasing, because every item on the left is at most A[k]A[k] and every item on the right is at least A[k]A[k]. It has the multiset of BB. A multiset has exactly one non-decreasing list, so this list is sort⁡(B)\operatorname{sort}(B). Read off the parts. □\square

Theorem. TRIMMED-MEAN returns 1n−2g∑i=g+1n−gx(i)\frac{1}{n-2g}\sum_{i=g+1}^{n-g} x_{(i)}.

Proof. Line L1 makes AA a copy of xx, so sort⁡(A)=(x(1),…,x(n))\operatorname{sort}(A) = (x_{(1)}, \ldots, x_{(n)}). By Lemmas 2 and 3, after line L3,

{ ⁣{A[0…g−1]} ⁣}={ ⁣{x(1),…,x(g)} ⁣},{ ⁣{A[g…n−1]} ⁣}={ ⁣{x(g+1),…,x(n)} ⁣}.\{\!\{A[0 \ldots g-1]\}\!\} = \{\!\{x_{(1)}, \ldots, x_{(g)}\}\!\}, \qquad \{\!\{A[g \ldots n-1]\}\!\} = \{\!\{x_{(g+1)}, \ldots, x_{(n)}\}\!\}.

Line L4 changes only A[g…n−1]A[g \ldots n-1]. Its sorted content is (x(g+1),…,x(n))(x_{(g+1)}, \ldots, x_{(n)}), and the position n−g−1n - g - 1 is at offset j=n−2g−1j = n - 2g - 1 in it. By Lemmas 2 and 3, afterwards

{ ⁣{A[g…n−g−2]} ⁣}={ ⁣{x(g+1),…,x(n−g−1)} ⁣},A[n−g−1]=x(n−g).\{\!\{A[g \ldots n-g-2]\}\!\} = \{\!\{x_{(g+1)}, \ldots, x_{(n-g-1)}\}\!\}, \qquad A[n-g-1] = x_{(n-g)}.

So { ⁣{A[g…n−g−1]} ⁣}={ ⁣{x(g+1),…,x(n−g)} ⁣}\{\!\{A[g \ldots n-g-1]\}\!\} = \{\!\{x_{(g+1)}, \ldots, x_{(n-g)}\}\!\}. A sum does not depend on the order of its terms, so line L5 computes s=∑i=g+1n−gx(i)s = \sum_{i=g+1}^{n-g} x_{(i)}, and line L6 divides by the count n−2g≥1n - 2g \ge 1, which line L2 checks. □\square

Expected cost. Each round of SELECT costs at most hi′−lo′+1hi' - lo' + 1 comparisons. With a uniform random pivot, the window keeps at most 3/43/4 of its items with probability at least 1/21/2: this holds when the pivot rank lies in the middle half. So the expected number of rounds before the window size drops below (3/4)jm(3/4)^j m is at most 2 per level jj, and the expected total is at most ∑j2(3/4)jm=8m\sum_j 2 (3/4)^j m = 8m comparisons for a range of mm items. The two calls cost at most 8n+8(n−g)8n + 8(n - g) in expectation, and lines L1, L5 and L6 cost O(n)O(n). In the worst case each round removes one item, which gives O(m2)O(m^2).

Complexity

  • Time. Each SELECT takes expected Θ(m)\Theta(m) comparisons on a range of mm items, and at most Θ(m2)\Theta(m^2). The two calls work on nn and n−gn - g items, and the sum takes n−2gn - 2g additions. So the expected time is Θ(n)\Theta(n) and the worst case is Θ(n2)\Theta(n^2). With the median of medians pivot rule, SELECT and the whole method take Θ(n)\Theta(n) in the worst case.
  • Space. Θ(n)\Theta(n) for the copy AA. If you may change the input, the method runs in place with O(1)O(1) extra words.
  • Sorting. Sorting and summing the middle takes Θ(nlog⁡n)\Theta(n \log n). It is simpler and fast enough for most samples. The selection method matters for large nn or for repeated use.

In exact arithmetic (integers or fractions) the result is exact. In floating point the sum in line L5 has the usual rounding error of a sum. Use Kahan summation or math.fsum for long samples.

Properties

  • Breakdown point (g+1)/n(g + 1)/n, which tends to α\alpha. The breakdown point page proves it: the kept values stay inside the range of the clean points as long as at most gg points are replaced.
  • Influence function. At a law FF symmetric about μ\mu with quantile q=F−1(1−α)q = F^{-1}(1 - \alpha), it is (x−μ)/(1−2α)(x - \mu)/(1 - 2\alpha) for ∣x−μ∣≤q|x - \mu| \le q, and ±q/(1−2α)\pm q/(1 - 2\alpha) outside. It is bounded but not redescending (cited, Huber and Ronchetti 2009, Chapter 3).
  • Asymptotic variance. For symmetric FF, it is the variance of the α\alpha-Winsorized law divided by (1−2α)2(1 - 2\alpha)^2. Stigler (1973) gave the limit law for every FF; when the cut quantiles are not unique, the limit is not normal.
  • Efficiency at the normal. A numerical integration gives these efficiencies relative to the mean:
α\alpha 0.05 0.10 0.20 0.25
efficiency 0.974 0.943 0.874 0.837

At the median end the efficiency tends to 2/π≈0.6372/\pi \approx 0.637. For heavy tails, such as a tt law with 3 degrees of freedom, the trimmed mean beats the mean by a wide margin.

  • Equivariance. xˉα\bar x_\alpha is location and scale equivariant: (ax+b)‾α=a xˉα+b\overline{(a x + b)}_\alpha = a\,\bar x_\alpha + b for a≠0a \ne 0.
  • An L-estimator. It is a linear combination of order statistics with weights 1/(n−2g)1/(n-2g) in the middle and 0 at the ends.

Variants and improvements

  • Winsorized mean. Replace the gg smallest values by x(g+1)x_{(g+1)} and the gg largest by x(n−g)x_{(n-g)}, then average. It has the same breakdown point.
  • Tukey and McLaughlin standard error. Use sw/((1−2α)n)s_w/((1 - 2\alpha)\sqrt n), where sw2s_w^2 is the sample variance of the Winsorized sample. Yuen's trimmed tt test uses it for two samples with unequal variances.
  • Asymmetric trimming. Cut g1g_1 values at the bottom and g2g_2 at the top. It estimates a different parameter when FF is skewed.
  • Interquartile mean. The case α=1/4\alpha = 1/4.
  • Adaptive trimming. Choose α\alpha from the data, for example from a measure of tail weight.
  • Streaming. Over a sliding window, keep the window in an order-statistic tree; see the sliding window median for the same structure.

When to use it

Use a trimmed mean when the data are roughly symmetric but may have a few gross errors or heavy tails, and you want an estimate that is easy to explain. Sports judging, price indices and many lab protocols use it. Use the median if up to half of the data can be bad. Use the Huber M-estimator if you want a smoother weighting and a better efficiency at the same robustness. Use the plain mean if the data are clean and light-tailed.

Pitfalls

  • g=0g = 0 for small samples. With α=0.1\alpha = 0.1 and n≤9n \le 9, g=0g = 0, and the trimmed mean is the mean, with breakdown point 1/n1/n.
  • Rounding of αn\alpha n. In floating point, 0.29×100=28.9999999999999960.29 \times 100 = 28.999999999999996, so ⌊αn⌋\lfloor \alpha n \rfloor gives 28 and not 29. Compute gg in exact arithmetic, or take gg as the input.
  • Skewed data. For a skewed FF, the trimmed mean estimates neither the mean nor the median of FF. It estimates its own functional.
  • Standard error. Do not use s/n−2gs/\sqrt{n - 2g} with the variance of the kept values. It is too small. Use the Winsorized variance.
  • Ties at the cut. With ties at x(g)=x(g+1)x_{(g)} = x_{(g+1)}, the kept multiset is still well defined. A three-way partition keeps the time linear when many values are equal.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

trimmed_mean.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trimmed-mean/. The authors are listed in prov/4F0CN9.jsonl.

import math
import random
from fractions import Fraction


def trim_count(n: int, alpha) -> int:
    """Return g = floor(alpha * n), computed exactly.

    A float alpha is read through its decimal repr, so 0.29 * 100 gives 29 and
    not 28 (the float product is 28.999999999999996).
    """
    a = Fraction(repr(alpha)) if isinstance(alpha, float) else Fraction(alpha)
    if not 0 <= a < Fraction(1, 2):
        raise ValueError("alpha must be in [0, 1/2)")
    return math.floor(a * n)


def select(a: list, lo: int, hi: int, k: int, rng: random.Random) -> None:
    """Rearrange a[lo..hi] in place so that a[k] is the value of rank k - lo.

    Afterwards a[lo..k-1] <= a[k] <= a[k+1..hi]. Quickselect with a random pivot
    and a three-way partition, so equal keys cost no extra time.
    Expected O(hi - lo + 1) comparisons.
    """
    while lo < hi:
        p = a[rng.randint(lo, hi)]
        lt, i, gt = lo, lo, hi  # a[lo..lt-1] < p, a[lt..i-1] == p, a[gt+1..hi] > p
        while i <= gt:
            if a[i] < p:
                a[lt], a[i] = a[i], a[lt]
                lt += 1
                i += 1
            elif a[i] > p:
                a[i], a[gt] = a[gt], a[i]
                gt -= 1
            else:
                i += 1
        if k < lt:
            hi = lt - 1
        elif k > gt:
            lo = gt + 1
        else:
            return


def trimmed_mean(xs, alpha=0.1, *, g=None, seed: int = 0):
    """Return the mean of x_(g+1), ..., x_(n-g), with g = floor(alpha * n).

    Pass g to set the number of points cut from each end directly. The input is
    not changed. Exact for int and Fraction data (the result is a Fraction).
    Expected Theta(n) time, Theta(n) extra space for the copy.
    """
    a = list(xs)
    n = len(a)  # @line L1
    if g is None:
        g = trim_count(n, alpha)  # @line L1
    if g < 0 or n - 2 * g < 1:  # @line L2
        raise ValueError("need n - 2 g >= 1")
    rng = random.Random(seed)
    select(a, 0, n - 1, g, rng)  # @line L3
    select(a, g, n - 1, n - g - 1, rng)  # @line L4
    s = sum(a[g:n - g], Fraction(0)) if all(isinstance(v, (int, Fraction)) for v in a) else math.fsum(a[g:n - g])  # @line L5
    return s / (n - 2 * g)  # @line L6


def winsorized_variance(xs, g: int):
    """Sample variance of the g-Winsorized sample (divide by n - 1).

    The Tukey-McLaughlin standard error of the trimmed mean is
    sqrt(winsorized_variance) / ((1 - 2 g / n) sqrt(n)).
    """
    s = sorted(xs)
    n = len(s)
    w = [s[g]] * g + s[g:n - g] + [s[n - g - 1]] * g
    m = sum(w) / n
    return sum((v - m) ** 2 for v in w) / (n - 1)
test_trimmed_mean.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trimmed-mean/. The authors are listed in prov/4F0CN9.jsonl.

import random
from fractions import Fraction

import pytest

from trimmed_mean import select, trim_count, trimmed_mean, winsorized_variance


def by_sorting(xs, g):
    """Oracle: sort, cut g values from each end, average exactly."""
    s = sorted(xs)
    kept = s[g:len(s) - g]
    return sum(kept, Fraction(0)) / len(kept)


def test_small_samples_by_hand() -> None:
    # sorted: 1 1 2 3 3 4 5 5 6 9; g = 2 keeps 2 3 3 4 5 5, sum 22.
    xs = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
    assert trimmed_mean(xs, Fraction(1, 5)) == Fraction(22, 6)
    # g = 0 is the mean, 39 / 10.
    assert trimmed_mean(xs, 0) == Fraction(39, 10)
    # g = 4 keeps 3 and 4.
    assert trimmed_mean(xs, g=4) == Fraction(7, 2)
    # (2, 4, 4, 5, 7, 9, 30) with g = 1 keeps 4 4 5 7 9.
    assert trimmed_mean([2, 4, 4, 5, 7, 9, 30], g=1) == Fraction(29, 5)
    # the example of the page
    # sorted: 1 3 4 5 6 7 8 10 12 95; g = 2 keeps 4 5 6 7 8 10, sum 40.
    assert trimmed_mean([12, 7, 3, 95, 5, 8, 6, 1, 10, 4], Fraction(1, 5)) == Fraction(20, 3)


def test_trim_count_is_exact() -> None:
    assert trim_count(100, 0.29) == 29
    assert trim_count(10, 0.1) == 1
    assert trim_count(7, 0.1) == 0
    assert trim_count(20, Fraction(1, 4)) == 5
    with pytest.raises(ValueError):
        trim_count(10, 0.5)


def test_against_sorting_random() -> None:
    rng = random.Random(1)
    for _ in range(400):
        n = rng.randint(1, 40)
        xs = [rng.randint(-5, 5) for _ in range(n)]  # many ties
        g = rng.randint(0, (n - 1) // 2)
        assert trimmed_mean(xs, g=g, seed=rng.randint(0, 10**6)) == by_sorting(xs, g)


def test_select_postcondition() -> None:
    rng = random.Random(2)
    for _ in range(300):
        n = rng.randint(1, 30)
        a = [rng.randint(0, 6) for _ in range(n)]
        lo = rng.randint(0, n - 1)
        hi = rng.randint(lo, n - 1)
        k = rng.randint(lo, hi)
        before = list(a)
        select(a, lo, hi, k, rng)
        assert a[:lo] == before[:lo] and a[hi + 1:] == before[hi + 1:]
        assert sorted(a[lo:hi + 1]) == sorted(before[lo:hi + 1])
        assert all(v <= a[k] for v in a[lo:k]) and all(v >= a[k] for v in a[k + 1:hi + 1])


def test_input_not_changed_and_float_data() -> None:
    xs = [0.5, 2.25, -1.0, 7.5, 3.0]
    copy = list(xs)
    assert trimmed_mean(xs, g=1) == pytest.approx((0.5 + 2.25 + 3.0) / 3)
    assert xs == copy


def test_empirical_breakdown() -> None:
    # Move k points to a huge value t. The trimmed mean stays in the range of the
    # clean points for k <= g, and grows without bound for k = g + 1.
    rng = random.Random(3)
    n, g = 20, 4
    clean = [rng.randint(0, 100) for _ in range(n)]
    for t in (10**6, 10**12, 10**30):
        for k in range(0, g + 2):
            ys = clean[:n - k] + [t] * k
            v = trimmed_mean(ys, g=g)
            lo, hi = min(clean[:n - k]), max(clean[:n - k])
            if k <= g:
                assert lo <= v <= hi
            else:
                assert v >= Fraction(t, n - 2 * g)
    # The mean (g = 0) breaks with one point.
    assert trimmed_mean(clean[:-1] + [10**30], g=0) > 10**28


def test_winsorized_variance_small() -> None:
    # g = 1 on (1, 2, 3, 4, 100): Winsorized sample (2, 2, 3, 4, 4), mean 3, variance 4 / 4.
    assert winsorized_variance([1, 2, 3, 4, 100], 1) == 1


def test_errors() -> None:
    with pytest.raises(ValueError):
        trimmed_mean([1, 2], g=1)
    with pytest.raises(ValueError):
        trimmed_mean([], 0)

History

Tukey and McLaughlin (1963) studied trimmed means for small samples and gave a tt-like statistic with a Winsorized variance. Bickel studied their large-sample behaviour in 1965. Stigler (1973) found the limit law for every distribution and showed that it can fail to be normal when a cut quantile is not unique. Yuen (1974) gave the two-sample trimmed tt test.

References

  1. John W. Tukey and Donald H. McLaughlin, Less vulnerable confidence and significance procedures for location based on a single sample, trimming/Winsorization 1, Sankhyā A 25(3), 1963, pp. 331 to 352 (the trimmed mean and its Winsorized standard error)
  2. Stephen M. Stigler, The asymptotic distribution of the trimmed mean, The Annals of Statistics 1(3), 1973, pp. 472 to 477 (the limit law of the trimmed mean for any distribution)
  3. Karen K. Yuen, The two-sample trimmed t for unequal population variances, Biometrika 61(1), 1974, pp. 165 to 170 (the trimmed t statistic with the Winsorized variance)
  4. Ricardo A. Maronna, R. Douglas Martin, Victor J. Yohai and Matías Salibián-Barrera, Robust Statistics, Theory and Methods (with R), second edition, Wiley, 2019, Chapter 2 (trimmed means, their variance and their efficiency at the normal)
  5. Peter J. Huber and Elvezio M. Ronchetti, Robust Statistics, second edition, Wiley, 2009, Chapter 3 (L-estimators, the trimmed mean and its influence function)
  6. Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, fourth edition, Section 9.2 (selection in expected linear time) and Section 9.3 (selection in worst-case linear time)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example