From 3d5f499fd6807186baf669eec491034766caab34 Mon Sep 17 00:00:00 2001 From: Malik Woods Date: Tue, 21 Oct 2014 15:24:50 -0700 Subject: BUG: upcast weights to average result type to avoid inaccuracies closes gh-5202 --- numpy/lib/function_base.py | 5 ++--- numpy/lib/tests/test_function_base.py | 5 +++++ 2 files changed, 7 insertions(+), 3 deletions(-) (limited to 'numpy/lib') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 0a1d05f77..aba18f799 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -510,8 +510,7 @@ def average(a, axis=None, weights=None, returned=False): scl = avg.dtype.type(a.size/avg.size) else: a = a + 0.0 - wgt = np.array(weights, dtype=a.dtype, copy=0) - + wgt = np.asarray(weights) # Sanity checks if a.shape != wgt.shape: if axis is None: @@ -528,7 +527,7 @@ def average(a, axis=None, weights=None, returned=False): # setup wgt to broadcast along axis wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1, axis) - scl = wgt.sum(axis=axis) + scl = wgt.sum(axis=axis, dtype=np.result_type(a.dtype, wgt.dtype)) if (scl == 0.0).any(): raise ZeroDivisionError( "Weights sum to zero, can't be normalized") diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index a3f805691..972d1aa1c 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -124,6 +124,11 @@ class TestAverage(TestCase): assert_array_equal(average(y1, weights=w2, axis=1), desired) assert_equal(average(y1, weights=w2), 5.) + y3 = rand(5).astype(np.float32) + w3 = rand(5).astype(np.float64) + + assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3)) + def test_returned(self): y = np.array([[1, 2, 3], [4, 5, 6]]) -- cgit v1.2.1