mean

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

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 O(r.length).

  1. T mean(R r)
    T
    mean
    (
    T = double
    R
    )
    (
    R r
    )
  2. auto mean(R r, T seed)

Parameters

T

The type of the return value.

r R

Return Value

Type: T

The mean of r when r is non-empty.

Examples

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.mean.isClose(2));
assert(arr2.mean.isClose(5.5));

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

Meta