sum

fnauto sum(R)(R r) if (isInputRange!R && !isInfinite!R && is(typeof(r.front + r.front)))

Sums elements of r, which must be a finite

input range. Although

conceptually sum(r) is equivalent to fold!((a, b) => a + b)(r, 0), sum uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point

    type and R is a

    random-access range with

    length and slicing, then sum uses the

    pairwise summation

    algorithm.

  • If ElementType!R is a floating-point type and R is a

    finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of

spec/type).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

Parameters

seedthe initial value of the summation
ra finite input range

Returns

The sum of all the elements in the range r.
fnauto sum(R, E)(R r, E seed) if (isInputRange!R && !isInfinite!R && is(typeof(seed = seed + r.front)))

ditto