8000 DOC: Mention and try to explain pairwise summation in sum (#13737) · numpy/numpy@871ed9b · GitHub 8000
[go: up one dir, main page]

Skip to content

Commit 871ed9b

Browse files
sebergmattip
authored andcommitted
DOC: Mention and try to explain pairwise summation in sum (#13737)
* DOC: Mention and try to explain pairwise summation in sum Note that this behaviour is of course inherited into `np.add.reduce` and many other reductions such as `mean` or users of this reduction, such as `cov`. This is ignored here.
1 parent 90d7191 commit 871ed9b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

numpy/core/fromnumeric.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2104,6 +2104,8 @@ def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
21042104
--------
21052105
ndarray.sum : Equivalent method.
21062106
2107+
add.reduce : Equivalent functionality of `add`.
2108+
21072109
cumsum : Cumulative sum of array elements.
21082110
21092111
trapz : Integration of array values using the composite trapezoidal rule.
@@ -2120,6 +2122,23 @@ def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
21202122
>>> np.sum([])
21212123
0.0
21222124
2125+
For floating point numbers the numerical precision of sum (and
2126+
``np.add.reduce``) is in general limited by directly adding each number
2127+
individually to the result causing rounding errors in every step.
2128+
However, often numpy will use a numerically better approach (partial
2129+
pairwise summation) leading to improved precision in many use-cases.
2130+
This improved precision is always provided when no ``axis`` is given.
2131+
When ``axis`` is given, it will depend on which axis is summed.
2132+
Technically, to provide the best speed possible, the improved precision
2133+
is only used when the summation is along the fast axis in memory.
2134+
Note that the exact precision may vary depending on other parameters.
2135+
In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2136+
more precise approach to summation.
2137+
Especially when summing a large number of lower precision floating point
2138+
numbers, such as ``float32``, numerical errors can become significant.
2139+
In such cases it can be advisable to use `dtype="float64"` to use a higher
2140+
precision for the output.
2141+
21232142
Examples
21242143
--------
21252144
>>> np.sum([0.5, 1.5])

0 commit comments

Comments
 (0)
0