File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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.
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments