Skip to content

Commit cf768a6

Browse files
sklamswap357
authored andcommitted
Merge pull request #10649 from swap357/fix_mean_issue_10647
Fix: `np.mean` precision for `float32`/`complex64` arrays
1 parent 5a7693a commit cf768a6

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Fix rounding error in ``mean`` for integer and boolean arrays
2+
-------------------------------------------------------------
3+
4+
Computing ``np.mean`` over an integer or boolean array cast the element count
5+
to the array's dtype before dividing, which could narrow the divisor and
6+
produce a slightly incorrect result. The division is now performed in full
7+
precision and only the final mean is cast, matching NumPy's result.

‎numba/np/arraymath.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ def array_mean_impl(a):
482482
c = acc_init
483483
for v in np.nditer(a):
484484
c += v.item()
485-
return c / dtype.type(a.size)
485+
return dtype.type(c / a.size)
486486
else:
487487
# For datetime/timedelta, don't add special empty array handling
488488
# Let it behave as before (NumPy itself raises error for empty

‎numba/tests/test_array_reductions.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,17 @@ def test_mean_empty_array(self):
505505
expected = np.mean(arr)
506506
self.assertPreciseEqual(cfunc(arr), expected)
507507

508+
def test_mean_count_rounding(self):
509+
# Reproducer from issue #10647: 2**24 + 1 is the smallest length
510+
# not exactly representable as float32, so any incorrect cast
511+
# in the computation will mismatch the np result.
512+
n = 2**24 + 1
513+
for dtype in (np.float32, np.complex64):
514+
arr = np.zeros(n, dtype=dtype)
515+
arr[0] = dtype(2**24 - 1)
516+
npr, nbr = run_comparative(array_mean, arr)
517+
self.assertPreciseEqual(npr, nbr)
518+
508519
def test_mean_empty_timedelta(self):
509520
"""Test that mean of empty timedelta array returns NaT"""
510521
cfunc = jit(nopython=True)(array_mean)

0 commit comments

Comments
 (0)