View source code
Display the source code in std/algorithm/iteration.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.algorithm.iteration.mean

Finds the mean (colloquially known as the average) of a range.

T mean(T, R) (
  R r
if (isInputRange!R && isNumeric!(ElementType!R) && !isInfinite!R);

auto mean(R, T) (
  R r,
  T seed
if (isInputRange!R && !isNumeric!(ElementType!R) && is(typeof(r.front + seed)) && is(typeof(r.front / size_t(1))) && !isInfinite!R);

For built-in numerical types, accurate Knuth & Welford mean calculation is used. For user-defined types, element by element summation is used. Additionally an extra parameter seed is needed in order to correctly seed the summation with the equivalent to 0.

The first overload of this function will return T.init if the range is empty. However, the second overload will return seed on empty ranges.

This function is Ο(r.length).


T The type of the return value.
r An input range
seed For user defined types. Should be equivalent to 0.


The mean of r when r is non-empty.


import std.math.operations : isClose;
import std.math.traits : isNaN;

static immutable arr1 = [1, 2, 3];
static immutable arr2 = [1.5, 2.5, 12.5];


assert(arr1[0 .. 0].mean.isNaN);


Andrei Alexandrescu


Boost License 1.0.