I was reviewing the itertools recipes to see whether some were worth promoting to be builtin tools. The dotproduct() recipe was the best candidate. To non-matrix people this is known as
and it comes up in many non-vector applications, possibly the most common being sum([price * quantity for price, quantity in zip(prices, quantities)]) and the second most common being weighted averages.
The current version of the recipe is:
def dotproduct(vec1, vec2): "Compute a sum of products." return sum(starmap(operator.mul, zip(vec1, vec2, strict=True))) If we offered this as part of the math module, we could make a higher quality implementation.
For float inputs or mixed int/float inputs, we could square and sum in
, making a single rounding at the end. This would make a robust building block to serve as a foundation for users to construct higher level tools. It is also something that is difficult for them to do on their own.
Linked PRs
GH-100485: Add math.sumprod() #100677
GH-100485: Convert from Fast2Sum to 2Sum #100836
GH-100485: Tweaks to sumprod() #100857
GH-100485: Add extended accuracy test. Switch to faster fma() based variant. #101383