Programming Search⌘K

Taskintro

Compute the mean and median

Also called average of a list, arithmetic mean, median of a list, mode of a list, statistics.mean, statistics.median, average(), Enumerable.Average, middle value.

Compute the arithmetic mean and the median of a list of integers. The mean needs a floating-point division, and the median of an even-length list is the mean of the two middle values.

Task

Compute the arithmetic mean and the median of a non-empty list of integers.

  • The mean is the sum of the items divided by the count. It is also called the arithmetic average1.
  • The median is the middle value of the sorted list. The Rosetta Code median task says that a solution "must handle the case where there are an even number of elements", and for that case it says: "return the average of the two middle values"2. Wikipedia gives the same rule: "If the data set has an even number of observations, there is no distinct middle value and the median is usually defined to be the arithmetic mean of the two middle values"3.

The function mean_and_median(items) returns the pair (mean, median) as floating-point numbers. For example, mean_and_median([1, 2, 3, 4, 100]) is (22.0, 3.0), and mean_and_median([4, 1, 3, 2]) is (2.5, 2.5). The example shows why the median is useful: one large value moves the mean far, but not the median.

The items are 64-bit signed integers, and the list is not empty. The mean of an empty list has no value, and the Rosetta Code task says that "if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it"1. The results are floating-point numbers, so the checker compares them with an absolute tolerance of 1e-9 or a relative tolerance of 1e-12.

The mode is the most frequent value. A list can have more than one mode, and Rosetta Code says: "Care must be taken to handle the case where the mode is non-unique"4. The Python example below shows it.

Solutions

Language Mean Median
Python statistics.mean(items) statistics.median(items)
JavaScript, TypeScript sum with reduce, then divide by length sort a copy with a compare function
Java LongStream.of(items).asDoubleStream().average() sort a copy with Arrays.sort
C# items.Average(x => (double)x) sort a copy with Order()
Go sum as float64 in a loop slices.Sorted(slices.Values(items))
Rust sum as f64 with map and sum to_vec(), then sort_unstable()
C sum as double in a loop qsort of a copy
C++ std::accumulate with the start value 0.0 std::nth_element on a copy
Bash awk sort -n, then awk
  • Python. statistics.mean "Return the sample arithmetic mean of data"5. It is exact for integers. statistics.fmean is faster, and "it always returns a float"5. statistics.median uses "the common “mean of middle two” method"5. All of them raise StatisticsError for empty data.
  • JavaScript. There is no mean or median function. The solution sums the items, and sorts a copy with (a, b) => a - b for the median. A 64-bit integer above 2 to the power 53 is not exact in a number, but the results are floating-point numbers, so the error is small.
  • TypeScript. The same code as JavaScript, with the type number[].
  • Java. average() of a LongStream "Returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty"6. The solution converts the items to double first, because the long sum can overflow, as a pitfall shows.
  • C#. Enumerable.Average throws InvalidOperationException when the "source contains no elements"7. The selector x => (double)x makes the sum a double.
  • Go. slices.Sorted collects the values of an iterator into a new sorted slice8, so the caller's slice does not change.
  • Rust. The solution sorts a copy. select_nth_unstable "Reorders the slice such that the element at index is at a sort-order position"9, so it finds a middle value without a full sort.
  • C. The solution copies the items, sorts the copy with qsort, and sums them in a double.
  • C++. std::nth_element puts the element of a position in its sorted place, with the smaller elements before it10. It finds the median in linear time on average, without a full sort.
  • Bash. Bash arithmetic has only integers, so sort -n sorts the items, and awk computes the mean and the median. The function prints them with the awk format %.17g, which shows each digit of a double.

The Python functions, with the mode:

import statistics

data = [1, 2, 3, 4, 100]
print(statistics.mean(data), statistics.median(data))
print(statistics.median([4, 1, 3, 2]))
print(statistics.median_low([4, 1, 3, 2]), statistics.median_high([4, 1, 3, 2]))
print(statistics.mode([1, 2, 2, 3, 3]), statistics.multimode([1, 2, 2, 3, 3]))
Output
22 3
2.5
2 3
2 [2, 3]

statistics.mean of integers gives the integer 22 here, because the mean is exact. median_low and median_high return a member of the data. mode "returns the first one encountered in the data"5 when there are many modes, and multimode returns all of them.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • odd, even and skewed: an odd count has one middle value, and an even count has two.
  • single: the mean and the median of one item are the item.
  • two-items: the median is the mean of both items.
  • negative: negative items.
  • unsorted-even: the items must be sorted first. The median of [10, 2, 8, 4] is 6.
  • duplicates: the mean is 2 and the median is 1.
  • not-an-integer: the mean of [1, 2, 2] is 5/3. An integer division gives 1.
  • large: the sum of two items near the 64-bit limit does not fit in 64 bits. An integer sum overflows.

Pitfalls

  • An integer division drops the fraction. In Go, Java, C, C++ and C#, the division of two integers gives an integer. Convert to a floating-point type before the division. See Integer division and modulo:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func main() {
	items := []int{1, 2, 2}
	sum := 0
	for _, x := range items {
		sum += x
	}
	fmt.Println(sum / len(items))
	fmt.Println(float64(sum) / float64(len(items)))
}
Output
1
1.6666666666666667
  • The sum overflows. A mean of large integers needs a sum that does not fit. In Java, the long sum inside LongStream.average() wraps around, so the mean of two copies of Long.MAX_VALUE is -1.0. A DoubleStream sum does not overflow, and it "may be implemented using compensated summation or other technique to reduce the error bound"11:

This code runs but gives a wrong answer on purpose.

import java.util.stream.LongStream;

public class Main {
  public static void main(String[] args) {
    long[] items = {Long.MAX_VALUE, Long.MAX_VALUE};
    System.out.println(LongStream.of(items).average().getAsDouble());
    System.out.println(LongStream.of(items).asDoubleStream().average().getAsDouble());
  }
}
Output
-1.0
9.223372036854776E18

The same is true for the mean of the two middle values: (a + b) / 2 can overflow when a and b are large. Convert them to double first, or compute a + (b - a) / 2.

  • The default JavaScript sort compares strings. "The default sort order is ascending, built upon converting the elements into strings"12, so 10 comes before 2, and the median is wrong. Give a compare function:

This code runs but gives a wrong answer on purpose.

const items = [10, 2, 8, 4];
console.log([...items].sort());
console.log([...items].sort((a, b) => a - b));
Output
[ 10, 2, 4, 8 ]
[ 2, 4, 8, 10 ]
  • An in-place sort changes the caller's list. list.sort() in Python, Arrays.sort in Java and sort in JavaScript change the list. A median function that sorts its argument surprises the caller. Sort a copy, or use a function that makes one, such as sorted in Python or toSorted in JavaScript.

  • An even-length list has two middle values. Taking only items[n / 2] gives the upper middle value. For [1, 2, 3, 4] it gives 3, not 2.5.

  • The mean of an empty list. Python raises StatisticsError. In JavaScript, 0 / 0 is NaN with no error. Check for an empty list first:

import statistics

try:
    statistics.mean([])
except statistics.StatisticsError as e:
    print(type(e).__name__)
Output
StatisticsError

The selection algorithm that finds the median in linear time is on the algorithm site: quickselect.

Code

The build runs the native tests of each language in a pinned toolchain.

meanmedian.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import statistics


def mean_and_median(items: list[int]) -> tuple[float, float]:
    """Return the mean and the median of a non-empty list.

    statistics.mean and statistics.median raise StatisticsError for an
    empty list. Neither function changes the list.
    """
    return float(statistics.mean(items)), float(statistics.median(items))


def mean_and_median_loop(items: list[int]) -> tuple[float, float]:
    """Return the same pair with a sum and a sorted copy."""
    n = len(items)
    s = sorted(items)
    mid = n // 2
    median = s[mid] if n % 2 == 1 else (s[mid - 1] + s[mid]) / 2
    return sum(items) / n, float(median)
test_meanmedian.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import math
import statistics

import pytest

from meanmedian import mean_and_median, mean_and_median_loop

CASES = [
    ("odd", [3, 1, 2], (2.0, 2.0)),
    ("even", [4, 1, 3, 2], (2.5, 2.5)),
    ("skewed", [1, 2, 3, 4, 100], (22.0, 3.0)),
    ("single", [5], (5.0, 5.0)),
    ("two-items", [1, 2], (1.5, 1.5)),
    ("negative", [-3, -1, -2], (-2.0, -2.0)),
    ("unsorted-even", [10, 2, 8, 4], (6.0, 6.0)),
    ("duplicates", [1, 1, 1, 5], (2.0, 1.0)),
    ("not-an-integer", [1, 2, 2], (1.6666666666666667, 2.0)),
    ("large", [9223372036854775807, 9223372036854775807], (9.223372036854776e+18, 9.223372036854776e+18)),
]


def close(got, want):
    return math.isclose(got, want, rel_tol=1e-12, abs_tol=1e-9)


@pytest.mark.parametrize(("name", "items", "want"), CASES, ids=[c[0] for c in CASES])
def test_mean_and_median(name, items, want):
    before = list(items)
    for f in (mean_and_median, mean_and_median_loop):
        mean, median = f(items)
        assert close(mean, want[0]) and close(median, want[1])
    assert items == before


def test_empty_raises():
    with pytest.raises(statistics.StatisticsError):
        mean_and_median([])
meanmedian.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

#ifndef MEAN_AND_MEDIAN_HPP
#define MEAN_AND_MEDIAN_HPP

#include <algorithm>
#include <cstddef>
#include <numeric>
#include <stdexcept>
#include <utility>
#include <vector>

// Returns the mean and the median of a non-empty vector. The start value
// 0.0 makes the sum a double. nth_element works on a copy.
inline std::pair<double, double> mean_and_median(const std::vector<long long>& items) {
    if (items.empty()) {
        throw std::invalid_argument("the list is empty");
    }
    const std::size_t n = items.size();
    const double mean =
        std::accumulate(items.begin(), items.end(), 0.0,
                        [](double a, long long x) { return a + static_cast<double>(x); }) /
        static_cast<double>(n);
    std::vector<long long> s = items;
    const auto mid = s.begin() + static_cast<std::ptrdiff_t>(n / 2);
    std::nth_element(s.begin(), mid, s.end());
    double median = static_cast<double>(*mid);
    if (n % 2 == 0) {
        // The elements before mid are not larger, so the lower middle is their maximum.
        const double low = static_cast<double>(*std::max_element(s.begin(), mid));
        median = (low + median) / 2;
    }
    return {mean, median};
}

#endif
test_meanmedian.cpp 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <stdexcept>
#include <vector>

#include "meanmedian.hpp"

namespace {

struct test_case {
    const char* name;
    std::vector<long long> items;
    double mean, median;
};

const test_case cases[] = {
    {"odd", {3, 1, 2}, 2.0, 2.0},
    {"even", {4, 1, 3, 2}, 2.5, 2.5},
    {"skewed", {1, 2, 3, 4, 100}, 22.0, 3.0},
    {"single", {5}, 5.0, 5.0},
    {"two-items", {1, 2}, 1.5, 1.5},
    {"negative", {-3, -1, -2}, -2.0, -2.0},
    {"unsorted-even", {10, 2, 8, 4}, 6.0, 6.0},
    {"duplicates", {1, 1, 1, 5}, 2.0, 1.0},
    {"not-an-integer", {1, 2, 2}, 1.6666666666666667, 2.0},
    {"large", {9223372036854775807LL, 9223372036854775807LL}, 9223372036854775808.0, 9223372036854775808.0},
};

bool close_to(double got, double want) {
    return std::abs(got - want) <= std::max(1e-9, 1e-12 * std::abs(want));
}

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const auto [mean, median] = mean_and_median(c.items);
        if (!close_to(mean, c.mean) || !close_to(median, c.median)) {
            std::printf("FAIL %s: (%.17g, %.17g)\n", c.name, mean, median);
            ++failures;
        }
    }
    try {
        mean_and_median({});
        std::printf("FAIL empty\n");
        ++failures;
    } catch (const std::invalid_argument&) {
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
MeanMedian.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import java.util.Arrays;
import java.util.stream.LongStream;

/** The mean and the median of a list of long values. */
public final class MeanMedian {
    private MeanMedian() {}

    /** Returns {mean, median} of a non-empty array. The array does not change. */
    public static double[] meanAndMedian(long[] items) {
        // A double sum does not overflow; the long sum of average() can.
        double mean = LongStream.of(items).asDoubleStream().average().orElseThrow();
        long[] s = items.clone();
        Arrays.sort(s);
        int mid = s.length / 2;
        double median = s.length % 2 == 1 ? s[mid] : ((double) s[mid - 1] + s[mid]) / 2;
        return new double[] {mean, median};
    }
}
MeanMedianTest.java 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.NoSuchElementException;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class MeanMedianTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("odd", new long[]{3, 1, 2}, 2.0, 2.0),
                Arguments.of("even", new long[]{4, 1, 3, 2}, 2.5, 2.5),
                Arguments.of("skewed", new long[]{1, 2, 3, 4, 100}, 22.0, 3.0),
                Arguments.of("single", new long[]{5}, 5.0, 5.0),
                Arguments.of("two-items", new long[]{1, 2}, 1.5, 1.5),
                Arguments.of("negative", new long[]{-3, -1, -2}, -2.0, -2.0),
                Arguments.of("unsorted-even", new long[]{10, 2, 8, 4}, 6.0, 6.0),
                Arguments.of("duplicates", new long[]{1, 1, 1, 5}, 2.0, 1.0),
                Arguments.of("not-an-integer", new long[]{1, 2, 2}, 1.6666666666666667, 2.0),
                Arguments.of("large", new long[]{9223372036854775807L, 9223372036854775807L}, 9223372036854775808.0, 9223372036854775808.0)
        );
    }

    static boolean close(double got, double want) {
        return Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void meanAndMedian(String name, long[] items, double mean, double median) {
        long[] before = items.clone();
        double[] got = MeanMedian.meanAndMedian(items);
        assertTrue(close(got[0], mean), "mean = " + got[0]);
        assertTrue(close(got[1], median), "median = " + got[1]);
        assertArrayEquals(before, items);
    }

    @Test
    void emptyThrows() {
        assertThrows(NoSuchElementException.class, () -> MeanMedian.meanAndMedian(new long[0]));
    }
}
meanmedian.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

#include "meanmedian.h"

#include <stdlib.h>
#include <string.h>

static int compare(const void *a, const void *b) {
    long long x = *(const long long *)a;
    long long y = *(const long long *)b;
    return (x > y) - (x < y);
}

bool mean_and_median(const long long *items, size_t n, double *mean, double *median) {
    if (n == 0) {
        return false;
    }
    long long *s = malloc(n * sizeof *s);
    if (s == NULL) {
        return false;
    }
    memcpy(s, items, n * sizeof *s);
    qsort(s, n, sizeof *s, compare);
    double sum = 0;
    for (size_t i = 0; i < n; i++) {
        sum += (double)items[i];
    }
    size_t mid = n / 2;
    *mean = sum / (double)n;
    *median = n % 2 == 1 ? (double)s[mid] : ((double)s[mid - 1] + (double)s[mid]) / 2;
    free(s);
    return true;
}
meanmedian.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

#ifndef MEAN_AND_MEDIAN_H
#define MEAN_AND_MEDIAN_H

#include <stdbool.h>
#include <stddef.h>

// Sets *mean and *median for the n items and returns true. Returns false
// if n is 0 or if the copy cannot be allocated. The items do not change.
bool mean_and_median(const long long *items, size_t n, double *mean, double *median);

#endif
test_meanmedian.c 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

#include "meanmedian.h"

#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    long long items[5];
    size_t n;
    double mean, median;
};

static const struct test_case cases[] = {
    {"odd", {3, 1, 2}, 3, 2.0, 2.0},
    {"even", {4, 1, 3, 2}, 4, 2.5, 2.5},
    {"skewed", {1, 2, 3, 4, 100}, 5, 22.0, 3.0},
    {"single", {5}, 1, 5.0, 5.0},
    {"two-items", {1, 2}, 2, 1.5, 1.5},
    {"negative", {-3, -1, -2}, 3, -2.0, -2.0},
    {"unsorted-even", {10, 2, 8, 4}, 4, 6.0, 6.0},
    {"duplicates", {1, 1, 1, 5}, 4, 2.0, 1.0},
    {"not-an-integer", {1, 2, 2}, 3, 1.6666666666666667, 2.0},
    {"large", {9223372036854775807LL, 9223372036854775807LL}, 2, 9223372036854775808.0, 9223372036854775808.0},
};

// The test does not use fabs, so it needs no math library.
static bool close_to(double got, double want) {
    double d = got - want;
    double w = want < 0 ? -want : want;
    double tol = 1e-12 * w > 1e-9 ? 1e-12 * w : 1e-9;
    return (d < 0 ? -d : d) <= tol;
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        double mean, median;
        if (!mean_and_median(c->items, c->n, &mean, &median) || !close_to(mean, c->mean) ||
            !close_to(median, c->median)) {
            printf("FAIL %s\n", c->name);
            failures++;
        }
    }
    double mean, median;
    if (mean_and_median(cases[0].items, 0, &mean, &median)) {
        printf("FAIL empty\n");
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
MeanMedian.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

using System.Linq;

/// <summary>The mean and the median of a list of long values.</summary>
public static class MeanMedian
{
    /// <summary>Returns the mean and the median of a non-empty array. The array does not change.</summary>
    public static (double Mean, double Median) MeanAndMedian(long[] items)
    {
        // The selector makes the sum a double, so it does not overflow.
        double mean = items.Average(x => (double)x);
        long[] s = items.Order().ToArray();
        int mid = s.Length / 2;
        double median = s.Length % 2 == 1 ? s[mid] : ((double)s[mid - 1] + s[mid]) / 2;
        return (mean, median);
    }
}
MeanMedianTests.cs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

using System;
using Xunit;

public sealed class MeanMedianTests
{
    public static TheoryData<string, long[], double, double> Cases => new()
    {
        { "odd", new long[] { 3, 1, 2 }, 2.0, 2.0 },
        { "even", new long[] { 4, 1, 3, 2 }, 2.5, 2.5 },
        { "skewed", new long[] { 1, 2, 3, 4, 100 }, 22.0, 3.0 },
        { "single", new long[] { 5 }, 5.0, 5.0 },
        { "two-items", new long[] { 1, 2 }, 1.5, 1.5 },
        { "negative", new long[] { -3, -1, -2 }, -2.0, -2.0 },
        { "unsorted-even", new long[] { 10, 2, 8, 4 }, 6.0, 6.0 },
        { "duplicates", new long[] { 1, 1, 1, 5 }, 2.0, 1.0 },
        { "not-an-integer", new long[] { 1, 2, 2 }, 1.6666666666666667, 2.0 },
        { "large", new long[] { 9223372036854775807, 9223372036854775807 }, 9223372036854775808.0, 9223372036854775808.0 },
    };

    private static bool Close(double got, double want) =>
        Math.Abs(got - want) <= Math.Max(1e-9, 1e-12 * Math.Abs(want));

    [Theory]
    [MemberData(nameof(Cases))]
    public void MeanAndMedian(string name, long[] items, double mean, double median)
    {
        Assert.NotNull(name);
        long[] before = (long[])items.Clone();
        var (m, med) = MeanMedian.MeanAndMedian(items);
        Assert.True(Close(m, mean), $"mean = {m}");
        Assert.True(Close(med, median), $"median = {med}");
        Assert.Equal(before, items);
    }

    [Fact]
    public void EmptyThrows()
    {
        Assert.Throws<InvalidOperationException>(() => MeanMedian.MeanAndMedian([]));
    }
}
meanmedian.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

/** Returns [mean, median] of a non-empty array of numbers. */
export function meanAndMedian(items) {
  const n = items.length;
  const mean = items.reduce((a, x) => a + x, 0) / n;
  // The default sort compares strings, so give a compare function.
  const s = items.toSorted((a, b) => a - b);
  const mid = Math.floor(n / 2);
  const median = n % 2 === 1 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
  return [mean, median];
}
meanmedian.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { meanAndMedian } from "./meanmedian.js";

const cases = [
  ["odd", [3, 1, 2], [2, 2]],
  ["even", [4, 1, 3, 2], [2.5, 2.5]],
  ["skewed", [1, 2, 3, 4, 100], [22, 3]],
  ["single", [5], [5, 5]],
  ["two-items", [1, 2], [1.5, 1.5]],
  ["negative", [-3, -1, -2], [-2, -2]],
  ["unsorted-even", [10, 2, 8, 4], [6, 6]],
  ["duplicates", [1, 1, 1, 5], [2, 1]],
  ["not-an-integer", [1, 2, 2], [1.6666666666666667, 2]],
  ["large", [9223372036854775807, 9223372036854775807], [9223372036854775808, 9223372036854775808]],
];

const close = (got, want) => Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));

for (const [name, items, want] of cases) {
  test(name, () => {
    const before = [...items];
    const [mean, median] = meanAndMedian(items);
    assert.ok(close(mean, want[0]), `mean = ${mean}`);
    assert.ok(close(median, want[1]), `median = ${median}`);
    assert.deepEqual(items, before);
  });
}
meanmedian.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

/** Returns [mean, median] of a non-empty array of numbers. */
export function meanAndMedian(items: readonly number[]): [number, number] {
  const n = items.length;
  const mean = items.reduce((a, x) => a + x, 0) / n;
  // The default sort compares strings, so give a compare function.
  const s = items.toSorted((a, b) => a - b);
  const mid = Math.floor(n / 2);
  const median = n % 2 === 1 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;
  return [mean, median];
}
meanmedian.test.ts 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { meanAndMedian } from "./meanmedian.ts";

const cases: [string, number[], [number, number]][] = [
  ["odd", [3, 1, 2], [2, 2]],
  ["even", [4, 1, 3, 2], [2.5, 2.5]],
  ["skewed", [1, 2, 3, 4, 100], [22, 3]],
  ["single", [5], [5, 5]],
  ["two-items", [1, 2], [1.5, 1.5]],
  ["negative", [-3, -1, -2], [-2, -2]],
  ["unsorted-even", [10, 2, 8, 4], [6, 6]],
  ["duplicates", [1, 1, 1, 5], [2, 1]],
  ["not-an-integer", [1, 2, 2], [1.6666666666666667, 2]],
  ["large", [9223372036854775807, 9223372036854775807], [9223372036854775808, 9223372036854775808]],
];

const close = (got: number, want: number): boolean =>
  Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));

for (const [name, items, want] of cases) {
  test(name, () => {
    const before = [...items];
    const [mean, median] = meanAndMedian(items);
    assert.ok(close(mean, want[0]), `mean = ${mean}`);
    assert.ok(close(median, want[1]), `median = ${median}`);
    assert.deepEqual(items, before);
  });
}
meanmedian.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

// Package meanmedian computes the mean and the median of a slice of integers.
package meanmedian

import "slices"

// MeanAndMedian returns the mean and the median of a non-empty slice.
// slices.Sorted makes a sorted copy, so the slice of the caller does not
// change.
func MeanAndMedian(items []int64) (mean, median float64) {
	var sum float64
	for _, x := range items {
		sum += float64(x)
	}
	n := len(items)
	s := slices.Sorted(slices.Values(items))
	mid := n / 2
	if n%2 == 1 {
		median = float64(s[mid])
	} else {
		median = (float64(s[mid-1]) + float64(s[mid])) / 2
	}
	return sum / float64(n), median
}
meanmedian_test.go 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

package meanmedian

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name         string
	items        []int64
	mean, median float64
}{
	{"odd", []int64{3, 1, 2}, 2.0, 2.0},
	{"even", []int64{4, 1, 3, 2}, 2.5, 2.5},
	{"skewed", []int64{1, 2, 3, 4, 100}, 22.0, 3.0},
	{"single", []int64{5}, 5.0, 5.0},
	{"two-items", []int64{1, 2}, 1.5, 1.5},
	{"negative", []int64{-3, -1, -2}, -2.0, -2.0},
	{"unsorted-even", []int64{10, 2, 8, 4}, 6.0, 6.0},
	{"duplicates", []int64{1, 1, 1, 5}, 2.0, 1.0},
	{"not-an-integer", []int64{1, 2, 2}, 1.6666666666666667, 2.0},
	{"large", []int64{9223372036854775807, 9223372036854775807}, 9223372036854775808.0, 9223372036854775808.0},
}

func near(got, want float64) bool {
	return math.Abs(got-want) <= math.Max(1e-9, 1e-12*math.Abs(want))
}

func TestMeanAndMedian(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			before := slices.Clone(c.items)
			mean, median := MeanAndMedian(c.items)
			if !near(mean, c.mean) || !near(median, c.median) {
				t.Fatalf("got (%v, %v), want (%v, %v)", mean, median, c.mean, c.median)
			}
			if !slices.Equal(before, c.items) {
				t.Fatal("the slice changed")
			}
		})
	}
}
meanmedian.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

/// Returns the mean and the median of a non-empty slice. The sum is an
/// f64, so it does not overflow. The function sorts a copy.
pub fn mean_and_median(items: &[i64]) -> (f64, f64) {
    assert!(!items.is_empty(), "the list is empty");
    let n = items.len();
    let mean = items.iter().map(|&x| x as f64).sum::<f64>() / n as f64;
    let mut s = items.to_vec();
    s.sort_unstable();
    let mid = n / 2;
    let median = if n % 2 == 1 {
        s[mid] as f64
    } else {
        (s[mid - 1] as f64 + s[mid] as f64) / 2.0
    };
    (mean, median)
}
tests/meanmedian_test.rs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-mean-and-median/.

use algo_compute_the_mean_and_median::mean_and_median;

const CASES: &[(&str, &[i64], (f64, f64))] = &[
    ("odd", &[3, 1, 2], (2.0, 2.0)),
    ("even", &[4, 1, 3, 2], (2.5, 2.5)),
    ("skewed", &[1, 2, 3, 4, 100], (22.0, 3.0)),
    ("single", &[5], (5.0, 5.0)),
    ("two-items", &[1, 2], (1.5, 1.5)),
    ("negative", &[-3, -1, -2], (-2.0, -2.0)),
    ("unsorted-even", &[10, 2, 8, 4], (6.0, 6.0)),
    ("duplicates", &[1, 1, 1, 5], (2.0, 1.0)),
    ("not-an-integer", &[1, 2, 2], (1.6666666666666667, 2.0)),
    ("large", &[9223372036854775807, 9223372036854775807], (9223372036854775808.0, 9223372036854775808.0)),
];

fn close(got: f64, want: f64) -> bool {
    (got - want).abs() <= f64::max(1e-9, 1e-12 * want.abs())
}

#[test]
fn cases() {
    for &(name, items, (mean, median)) in CASES {
        let (gm, gd) = mean_and_median(items);
        assert!(close(gm, mean) && close(gd, median), "{name}: got ({gm}, {gd})");
    }
}

#[test]
#[should_panic(expected = "the list is empty")]
fn empty_panics() {
    mean_and_median(&[]);
}
meanmedian.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-mean-and-median/.

# mean_and_median ITEM...
# Prints "mean median". Bash arithmetic has only integers, so sort sorts the
# items and awk computes the results as floating-point numbers. Returns 1 if
# there are no items.
mean_and_median() {
  if [ "$#" -eq 0 ]; then
    return 1
  fi
  printf '%s\n' "$@" | sort -n | awk '
    { s[NR] = $1; sum += $1 }
    END {
      mid = int((NR + 1) / 2)
      median = NR % 2 == 1 ? s[mid] : (s[mid] + s[mid + 1]) / 2
      printf "%.17g %.17g\n", sum / NR, median
    }'
}
test_meanmedian.bats 30 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-mean-and-median/.

setup() {
  source "$BATS_TEST_DIRNAME/meanmedian.sh"
}

# close GOT_MEAN GOT_MEDIAN WANT_MEAN WANT_MEDIAN
close() {
  awk -v a="$1" -v b="$2" -v c="$3" -v d="$4" 'function ok(g, w,  e, t) {
    e = g - w; if (e < 0) e = -e
    t = w < 0 ? -w : w; t = t * 1e-12; if (t < 1e-9) t = 1e-9
    return e <= t
  }
  BEGIN { exit !(ok(a, c) && ok(b, d)) }'
}

@test "odd" { run mean_and_median 3 1 2; [ "$status" -eq 0 ]; close $output 2 2; }
@test "even" { run mean_and_median 4 1 3 2; [ "$status" -eq 0 ]; close $output 2.5 2.5; }
@test "skewed" { run mean_and_median 1 2 3 4 100; [ "$status" -eq 0 ]; close $output 22 3; }
@test "single" { run mean_and_median 5; [ "$status" -eq 0 ]; close $output 5 5; }
@test "two-items" { run mean_and_median 1 2; [ "$status" -eq 0 ]; close $output 1.5 1.5; }
@test "negative" { run mean_and_median -3 -1 -2; [ "$status" -eq 0 ]; close $output -2 -2; }
@test "unsorted-even" { run mean_and_median 10 2 8 4; [ "$status" -eq 0 ]; close $output 6 6; }
@test "duplicates" { run mean_and_median 1 1 1 5; [ "$status" -eq 0 ]; close $output 2 1; }
@test "not-an-integer" { run mean_and_median 1 2 2; [ "$status" -eq 0 ]; close $output 1.6666666666666667 2; }
@test "large" { run mean_and_median 9223372036854775807 9223372036854775807; [ "$status" -eq 0 ]; close $output 9223372036854775808 9223372036854775808; }

@test "empty-fails" { run mean_and_median; [ "$status" -eq 1 ]; }

References

  1. Rosetta Code, Averages/Arithmetic mean (task text, from acmeism/RosettaCodeData), task text
  2. Rosetta Code, Averages/Median (task text, from acmeism/RosettaCodeData), task text
  3. Wikipedia, Median, Finite set of numbers
  4. Rosetta Code, Averages/Mode (task text, from acmeism/RosettaCodeData), task text
  5. The Python Standard Library, statistics, mean; fmean; median; median_low; multimode
  6. Java SE 25 API, Interface LongStream, average()
  7. .NET API reference, Enumerable.Average method, Exceptions
  8. Go standard library, slices, func Sorted; func Sort
  9. Rust standard library, primitive type slice, select_nth_unstable
  10. cppreference.com, std::nth_element, the description of the function
  11. Java SE 25 API, Interface DoubleStream, sum()
  12. MDN Web Docs, Array.prototype.sort(), Description

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source