sum

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.

For floating point inputs, calculations are made in 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 integral promotion).

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.

  1. auto sum(R r)
    sum
    (
    R
    )
    (
    R r
    )
    if (
    is(typeof(r.front + r.front))
    )
  2. auto sum(R r, E seed)

Parameters

r R

a finite input range

Return Value

Type: auto

The sum of all the elements in the range r.

Examples

Ditto

1 import std.range;
2 
3 //simple integral sumation
4 assert(sum([ 1, 2, 3, 4]) == 10);
5 
6 //with integral promotion
7 assert(sum([false, true, true, false, true]) == 3);
8 assert(sum(ubyte.max.repeat(100)) == 25500);
9 
10 //The result may overflow
11 assert(uint.max.repeat(3).sum()           ==  4294967293U );
12 //But a seed can be used to change the sumation primitive
13 assert(uint.max.repeat(3).sum(ulong.init) == 12884901885UL);
14 
15 //Floating point sumation
16 assert(sum([1.0, 2.0, 3.0, 4.0]) == 10);
17 
18 //Floating point operations have double precision minimum
19 static assert(is(typeof(sum([1F, 2F, 3F, 4F])) == double));
20 assert(sum([1F, 2, 3, 4]) == 10);
21 
22 //Force pair-wise floating point sumation on large integers
23 import std.math : approxEqual;
24 assert(iota(ulong.max / 2, ulong.max / 2 + 4096).sum(0.0)
25            .approxEqual((ulong.max / 2) * 4096.0 + 4096^^2 / 2));

Meta

Suggestion Box / Bug Report