sum#

Add up every element of a PDL and return the total as a 0-dimensional PDL.

Calling it#

my $s = sum($pdl);   # function form
my $s = $pdl->sum;   # method form

Both forms accept any PDL, regardless of shape. The input is flattened and every element is added; nothing is broadcast. For per-row or per-column sums, use sumover (see See also below).

What you get back#

A 0-dimensional PDL — think of it as “a PDL holding one number”. It prints as a single number, compares numerically, and works inside PDL arithmetic. If you want a plain Perl scalar, pull it out with sclr:

my $n = $pdl->sum->sclr;   # ordinary Perl number

The element type of the result is promoted so the total can’t silently overflow:

Input type

Result type

signed integer

indx

unsigned integer

ulonglong

float / double

same

complex

same

This matches the “int+” promotion rule of the underlying engine. If you specifically want a double-precision result from an integer input, call dsum instead.

Examples#

Basic sum of a 1-D piddle:

my $x = pdl(1, 2, 3, 4, 5);
print $x->sum;             # 15

Sum of a 2-D piddle — every element, not row- or column-wise:

my $m = sequence(3, 4);    # 3×4 matrix, values 0..11
print $m->sum;             # 66

Floating-point accumulation follows IEEE-754 rules, so adding many small numbers to a large one can lose precision. For a more accurate sum of many floats, sort ascending before summing or use dsum to accumulate in double precision:

my $x = float(1e8, 1, 1, 1);
print $x->sum;             # 100000000   — the three 1s got lost
print $x->dsum;            # 100000003   — accumulates in double

Bad values#

If the input has its bad-value flag set, elements marked BAD are skipped:

my $b = pdl(1, 2, 3);
$b->badflag(1);
$b->inplace->setbadat(1);  # mark the middle element BAD
print $b->sum;             # 4

If every element is BAD, the returned 0-dim PDL is itself marked BAD and stringifies as "BAD".

Edge cases#

  • Empty PDL (any dim of size 0) — returns 0, marked BAD if the input has its bad-value flag set.

  • undef argument — returns a PDL holding 0. (Upstream PDL croaks here; see Differences from upstream PDL below.)

  • Non-PDL scalar (plain number or arrayref) — promoted to a PDL first, then summed. sum(5) returns 5; sum([1,2,3]) returns 6.

Differences from upstream PDL#

  • sum(undef) returns 0 rather than croaking with Can't call method "flat" on an undefined value. Scripts that rely on the croak for error detection need an explicit defined check. Covered by t/81-xs-native/PDL/030-reductions.t.

Otherwise behavior matches upstream PDL 2.103.

See also#

  • sumover — sum along the first dimension only

  • dsum — same as sum, accumulating in double precision

  • avg — arithmetic mean of all elements

  • prod — product of all elements

  • stats — mean, variance, min, max, median in one call