Qu

sum

Builtin index · Core maths

result = sum(x, [on_invalid=])

Input: x, on_invalid · Output: result

What it is

Sum of every element of x — a scalar, Vec, or Mat/Signal (real; additionally accepts a CVec/CMat and returns a Complex in that case). A boolean mask counts as 0/1, so sum(x <= c) is the number of elements satisfying the condition (0 for an all-false or empty mask). With no other argument, reduces to one scalar Num (or Complex). On a Mat, the optional axis= keyword (0 or 1) reduces along just that dimension instead, returning a Vec of length cols (axis=0) or rows (axis=1). on_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling, including for a CVec's complex elements — a NaN/Inf in either the real or the imaginary part counts.

Overloads

x can be scalar, Vec, Mat, Signal, CVec, or CMat; on_invalid can be scalar, Vec, Mat, Signal, CVec, or CMat.

2 forms. Each carries its own inputs, outputs and worked example — pick the tab for the one you are calling.

CodeInputOutputDescription
result = sum(x, [on_invalid=])
x scalar, Vec, Mat, or Signalx a real scalar, Vec, or Mat/Signal.
on_invalid scalar, Vec, Mat, or Signal, optionalon_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling, including for a CVec's complex elements — a NaN/Inf in either the real or the imaginary part counts.
result scalar or Num
Returns a real scalar Num.

Examples

Written for this form and run by the build -- the output below is what the engine actually produced.

print(sum([1, 2, 3]))   # 6

output
6
CodeInputOutputDescription
result = sum(x, [on_invalid=])
x CVec or CMatx a CVec or CMat.
on_invalid CVec or CMat, optionalon_invalid= ("propagate"/"ignore"/"error", see this section's intro) controls NaN/Inf handling, including for a CVec's complex elements — a NaN/Inf in either the real or the imaginary part counts.
result Complex, scalar, or Num
Returns a Complex scalar instead of a Num — the one reduction in this table that changes its own return *type* based on its input, rather than just its shape.

Examples

Written for this form and run by the build -- the output below is what the engine actually produced.

print(sum([1 + 1j, 2 + 2j]))   # 3 + 3j

output
3 + 3j

How it works

reductions sum is complex-aware: a CVec reduces to a Complex instead of erroring through the real-only to_vec coercion below -- DSP idioms like a DFT bin (sum(x .* twiddle_factors)) need it. on_invalid= (default "propagate", today's behavior unchanged) — see OnInvalid's doc comment for the three values and apply_on_invalid/arg_extremum_on_invalid for where each reduction below applies it.

From the note above this builtin in the interpreter, where the reasoning was written down as it was built.