Reference · Math

math.sumprod

signature
math.sumprod(list, list) -> num

What it does

The sum of the products of two lists item by item, a dot product, as Python's math.sumprod: math.sumprod([1, 2, 3], [4, 5, 6]) is 4 + 10 + 18, 32. Two lists of ints give an exact int; otherwise the products and the sum are taken as if in twice the precision and rounded once, so floats come out as exactly as math.fsum sums them. A quantity list times a price list is a total.

Examples

print(math.sumprod([1, 2, 3], [4, 5, 6]), math.sumprod([1.5, 2], [2, 3]))let quantities = [2, 1, 4]let prices = [9.99, 24.5, 0.75]print(math.sumprod(quantities, prices))
output
32 9.047.480000000000004

Edge cases

print(math.sumprod([], []), math.sumprod(null, null), math.sumprod([1, 2], [3, 4.0]))print(math.sumprod([1e100, 1, -1e100], [1, 1, 1]))
output
0 0 11.01.0
this one fails
print(math.sumprod([9223372036854775807, 1], [2, 1]))
output
line 1: integer overflow

Errors

Lists of different lengths are a runtime error, not an error value, as Python's ValueError; the message gives both lengths. A list item that is not a number, or an argument that is not a list, is a runtime error as well.

this one fails
print(math.sumprod([1, 2], [1]))
output
line 1: `math.sumprod` needs lists of the same length (2 and 1)
this one fails
print(math.sumprod([1, "2"], [3, 4]))
output
line 1: `math.sumprod` expects a list of numbers, but item 1 is str

Chaining

In a pipeline the first list comes first, so xs | math.sumprod(ys). A weighted total and a weighted mean:

let scores = [80, 90, 70]let weights = [0.5, 0.3, 0.2]print(scores | math.sumprod(weights))print(math.sumprod(scores, weights) / sum(weights))
output
81.081.0

See also

vec.dot, math.fsum, math.prod, stats.fmean

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On math.sumprod(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo