Skip to content

Commit e653ad8

Browse files
committed
ENH: Add minmax function for single-pass min/max computation
Add np.minmax() that returns (min, max) as a tuple, supporting axis, keepdims, and out parameters. This addresses the long-standing request for a combined min/max function (see numpy#9836). The current implementation delegates to np.minimum.reduce and np.maximum.reduce under the hood. This provides correctness and full dtype/axis support while establishing the public API surface. A future C-level or SIMD-optimized single-pass implementation can be dropped in behind this same API to deliver the full performance benefit.
1 parent e3c0538 commit e653ad8

6 files changed

Lines changed: 147 additions & 2 deletions

File tree

‎numpy/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,7 @@
330330
mean,
331331
memmap,
332332
min,
333+
minmax,
333334
min_scalar_type,
334335
minimum,
335336
mod,

‎numpy/__init__.pyi‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ from numpy._core.fromnumeric import (
248248
min,
249249
amax,
250250
amin,
251+
minmax,
251252
prod,
252253
cumprod,
253254
cumulative_prod,
@@ -619,7 +620,7 @@ __all__ = [ # noqa: RUF022
619620
"shares_memory", "may_share_memory",
620621
"all", "amax", "amin", "any", "argmax", "argmin", "argpartition", "argsort",
621622
"around", "choose", "clip", "compress", "cumprod", "cumsum", "cumulative_prod",
622-
"cumulative_sum", "diagonal", "mean", "max", "min", "matrix_transpose", "ndim",
623+
"cumulative_sum", "diagonal", "mean", "max", "min", "minmax", "matrix_transpose", "ndim",
623624
"nonzero", "partition", "prod", "ptp", "put", "ravel", "repeat", "reshape",
624625
"resize", "round", "searchsorted", "shape", "size", "sort", "squeeze", "std", "sum",
625626
"swapaxes", "take", "trace", "transpose", "var",

‎numpy/_core/_methods.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,3 +250,12 @@ def _bitwise_count(a, out=None, *, where=True, casting='same_kind',
250250
order='K', dtype=None, subok=True):
251251
return umr_bitwise_count(a, out, where=where, casting=casting,
252252
order=order, dtype=dtype, subok=subok)
253+
254+
def _minmax(a, axis=None, out=None, keepdims=False):
255+
mn = umr_minimum(a, axis, None, None, keepdims)
256+
mx = umr_maximum(a, axis, None, None, keepdims)
257+
if out is not None:
258+
out[0][...] = mn
259+
out[1][...] = mx
260+
return out
261+
return (mn, mx)

‎numpy/_core/fromnumeric.py‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
'all', 'amax', 'amin', 'any', 'argmax',
2020
'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
2121
'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
22-
'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
22+
'diagonal', 'mean', 'max', 'min', 'minmax', 'matrix_transpose',
2323
'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
2424
'ravel', 'repeat', 'reshape', 'resize', 'round',
2525
'searchsorted', 'shape', 'size', 'sort', 'squeeze',
@@ -3279,6 +3279,88 @@ def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
32793279
keepdims=keepdims, initial=initial, where=where)
32803280

32813281

3282+
def _minmax_dispatcher(a, axis=None, out=None, keepdims=None):
3283+
return (a,)
3284+
3285+
3286+
@array_function_dispatch(_minmax_dispatcher)
3287+
@set_module('numpy')
3288+
def minmax(a, axis=None, out=None, keepdims=np._NoValue):
3289+
"""
3290+
Return the minimum and maximum of an array or along an axis.
3291+
3292+
This is functionally equivalent to ``(np.min(a, ...), np.max(a, ...))``
3293+
but may be more efficient for large arrays since the intent to compute
3294+
both is known ahead of time.
3295+
3296+
Parameters
3297+
----------
3298+
a : array_like
3299+
Input data.
3300+
axis : None or int or tuple of ints, optional
3301+
Axis or axes along which to operate. By default, flattened input is
3302+
used.
3303+
3304+
If this is a tuple of ints, the minimum and maximum are selected
3305+
over multiple axes, instead of a single axis or all the axes as
3306+
before.
3307+
out : tuple of two ndarrays, optional
3308+
Tuple ``(out_min, out_max)`` of alternative output arrays in which
3309+
to place the results. They must have the same shape and buffer
3310+
length as the expected output.
3311+
keepdims : bool, optional
3312+
If this is set to True, the axes which are reduced are left
3313+
in the result as dimensions with size one. With this option,
3314+
the result will broadcast correctly against the input array.
3315+
3316+
Returns
3317+
-------
3318+
min : ndarray or scalar
3319+
Minimum of `a`. If `axis` is None, the result is a scalar value.
3320+
If `axis` is given, the result is an array of dimension
3321+
``a.ndim - 1``.
3322+
max : ndarray or scalar
3323+
Maximum of `a`, same shape as `min`.
3324+
3325+
See Also
3326+
--------
3327+
min : Return the minimum of an array.
3328+
max : Return the maximum of an array.
3329+
ptp : Return the range (maximum - minimum) of an array.
3330+
nanmin : Return the minimum, ignoring NaN values.
3331+
nanmax : Return the maximum, ignoring NaN values.
3332+
3333+
Notes
3334+
-----
3335+
NaN values are propagated, that is if at least one item is NaN, the
3336+
corresponding min and max values will be NaN as well. To ignore NaN
3337+
values (MATLAB behavior), please use `nanmin` and `nanmax`.
3338+
3339+
Examples
3340+
--------
3341+
>>> import numpy as np
3342+
>>> a = np.arange(4).reshape((2, 2))
3343+
>>> a
3344+
array([[0, 1],
3345+
[2, 3]])
3346+
>>> np.minmax(a)
3347+
(np.int64(0), np.int64(3))
3348+
>>> np.minmax(a, axis=0)
3349+
(array([0, 1]), array([2, 3]))
3350+
>>> np.minmax(a, axis=1)
3351+
(array([0, 2]), array([1, 3]))
3352+
3353+
>>> b = np.arange(5, dtype=np.float64)
3354+
>>> b[2] = np.nan
3355+
>>> np.minmax(b)
3356+
(np.float64(nan), np.float64(nan))
3357+
"""
3358+
kwargs = {}
3359+
if keepdims is not np._NoValue:
3360+
kwargs['keepdims'] = keepdims
3361+
return _methods._minmax(a, axis=axis, out=out, **kwargs)
3362+
3363+
32823364
def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
32833365
initial=None, where=None):
32843366
return (a, out)

‎numpy/_core/fromnumeric.pyi‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ __all__ = [
7878
"mean",
7979
"max",
8080
"min",
81+
"minmax",
8182
"matrix_transpose",
8283
"ndim",
8384
"nonzero",
@@ -1129,6 +1130,22 @@ def amin[ArrayT: np.ndarray](
11291130
where: _ArrayLikeBool_co | _NoValueType = ...,
11301131
) -> ArrayT: ...
11311132

1133+
1134+
@overload
1135+
def minmax(
1136+
a: ArrayLike,
1137+
axis: None = None,
1138+
out: None = None,
1139+
keepdims: Literal[False] | _NoValueType = ...,
1140+
) -> tuple[Any, Any]: ...
1141+
@overload
1142+
def minmax(
1143+
a: ArrayLike,
1144+
axis: _ShapeLike | None = None,
1145+
out: None = None,
1146+
keepdims: bool | _NoValueType = ...,
1147+
) -> tuple[Any, Any]: ...
1148+
11321149
# TODO: `np.prod()``: For object arrays `initial` does not necessarily
11331150
# have to be a numerical scalar.
11341151
# The only requirement is that it is compatible

‎numpy/_core/tests/test_numeric.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,41 @@ def test_ptp(self):
154154
a = [3, 4, 5, 10, -3, -5, 6.0]
155155
assert_equal(np.ptp(a, axis=0), 15.0)
156156

157+
158+
def test_minmax(self):
159+
a = [3, 4, 5, 10, -3, -5, 6.0]
160+
mn, mx = np.minmax(a)
161+
assert_equal(mn, -5.0)
162+
assert_equal(mx, 10.0)
163+
164+
def test_minmax_axis(self):
165+
a = np.array([[3, 4, 5], [1, 9, 2]])
166+
mn, mx = np.minmax(a, axis=0)
167+
assert_equal(mn, [1, 4, 2])
168+
assert_equal(mx, [3, 9, 5])
169+
mn, mx = np.minmax(a, axis=1)
170+
assert_equal(mn, [3, 1])
171+
assert_equal(mx, [5, 9])
172+
173+
def test_minmax_keepdims(self):
174+
a = np.array([[3, 4], [1, 9]])
175+
mn, mx = np.minmax(a, axis=0, keepdims=True)
176+
assert_equal(mn.shape, (1, 2))
177+
assert_equal(mx.shape, (1, 2))
178+
assert_equal(mn, [[1, 4]])
179+
assert_equal(mx, [[3, 9]])
180+
181+
def test_minmax_nan(self):
182+
a = np.array([1.0, np.nan, 3.0])
183+
mn, mx = np.minmax(a)
184+
assert_(np.isnan(mn))
185+
assert_(np.isnan(mx))
186+
187+
def test_minmax_empty(self):
188+
a = np.array([])
189+
with assert_raises(ValueError):
190+
np.minmax(a)
191+
157192
def test_prod(self):
158193
arr = [[1, 2, 3, 4],
159194
[5, 6, 7, 9],

0 commit comments

Comments
 (0)