Reference · Math
math.sumprod
math.sumprod(list, list) -> numWhat 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))32 9.047.480000000000004Edge cases
- Two empty lists give
0, an int;nullcounts as an empty list. - One float anywhere makes the result a float,
11.0for[1, 2]and[3, 4.0]. - Int products that pass what an int holds (about 9.2 × 10¹⁸) are a runtime error,
integer overflow, not a float. - The float sum is compensated:
[1e100, 1, -1e100]against ones gives1.0, where a plain loop gives0.0.
print(math.sumprod([], []), math.sumprod(null, null), math.sumprod([1, 2], [3, 4.0]))print(math.sumprod([1e100, 1, -1e100], [1, 1, 1]))0 0 11.01.0print(math.sumprod([9223372036854775807, 1], [2, 1]))line 1: integer overflowErrors
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.
print(math.sumprod([1, 2], [1]))line 1: `math.sumprod` needs lists of the same length (2 and 1)print(math.sumprod([1, "2"], [3, 4]))line 1: `math.sumprod` expects a list of numbers, but item 1 is strChaining
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))81.081.0See also
vec.dot, math.fsum, math.prod, stats.fmean
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