From 8cfc788643af035298a038410b73e044da695842 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Wed, 10 Jan 2018 23:26:39 -0800 Subject: [PATCH 1/2] ENH: Preserve norm dtype for order 0 --- numpy/linalg/linalg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index 8bc1b14d3f60..922bc8cc1b9a 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -2277,7 +2277,7 @@ def norm(x, ord=None, axis=None, keepdims=False): return abs(x).min(axis=axis, keepdims=keepdims) elif ord == 0: # Zero norm - return (x != 0).astype(float).sum(axis=axis, keepdims=keepdims) + return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims) elif ord == 1: # special case for speedup return add.reduce(abs(x), axis=axis, keepdims=keepdims) From 04896b0b470854c33e3eea15790a87a864941c50 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Wed, 10 Jan 2018 23:27:35 -0800 Subject: [PATCH 2/2] BUG: Avoid unintentional promotion to `float`, and do ops in place for speed Fixes gh-10364, partly by adjusting the promise in the release notes --- doc/release/1.14.0-notes.rst | 6 +++--- numpy/linalg/linalg.py | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/release/1.14.0-notes.rst b/doc/release/1.14.0-notes.rst index 793b20c6d867..7d83014a4f3c 100644 --- a/doc/release/1.14.0-notes.rst +++ b/doc/release/1.14.0-notes.rst @@ -179,10 +179,10 @@ functions, and if used would likely correspond to a typo. Previously, this would promote to ``float64`` when arbitrary orders were passed, despite not doing so under the simple cases:: - >>> f32 = np.float32([1, 2]) - >>> np.linalg.norm(f32, 2.0).dtype + >>> f32 = np.float32([[1, 2]]) + >>> np.linalg.norm(f32, 2.0, axis=-1).dtype dtype('float32') - >>> np.linalg.norm(f32, 2.0001).dtype + >>> np.linalg.norm(f32, 2.0001, axis=-1).dtype dtype('float64') # numpy 1.13 dtype('float32') # numpy 1.14 diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index 922bc8cc1b9a..e42de824cb45 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -2292,7 +2292,9 @@ def norm(x, ord=None, axis=None, keepdims=False): raise ValueError("Invalid norm order for vectors.") absx = abs(x) absx **= ord - return add.reduce(absx, axis=axis, keepdims=keepdims) ** (1.0 / ord) + ret = add.reduce(absx, axis=axis, keepdims=keepdims) + ret **= (1 / ord) + return ret elif len(axis) == 2: row_axis, col_axis = axis row_axis = normalize_axis_index(row_axis, nd)