From 3b8e0c4112c957410a93432b22b74971bc06f8f8 Mon Sep 17 00:00:00 2001 From: Alexis Placet Date: Wed, 6 May 2026 15:12:17 +0200 Subject: [PATCH] Fix clip function behavior when a_min is greater than a_max (#2909) # Checklist - [x] The title and commit message(s) are descriptive. - [x] Small commits made to fix your PR have been squashed to avoid history pollution. - [x] Tests have been added for new features or bug fixes. - [x] API of new functions and classes are documented. # Description Address #2860 Now `clips` follow the rule: When a_min is greater than a_max, clip returns an array in which all values are equal to a_max --------- Co-authored-by: Alexis Placet <2400067+Alex-PLACET@users.noreply.github.com> Co-authored-by: Copilot --- include/xtensor/core/xmath.hpp | 4 ++-- test/test_xmath.cpp | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/include/xtensor/core/xmath.hpp b/include/xtensor/core/xmath.hpp index 315e13a82..827e84219 100644 --- a/include/xtensor/core/xmath.hpp +++ b/include/xtensor/core/xmath.hpp @@ -606,13 +606,13 @@ namespace xt template constexpr auto operator()(const A1& v, const A2& lo, const A3& hi) const { - return xtl::select(v < lo, lo, xtl::select(hi < v, hi, v)); + return xtl::select(lo < hi, xtl::select(v < lo, lo, xtl::select(hi < v, hi, v)), hi); } template constexpr auto simd_apply(const A1& v, const A2& lo, const A3& hi) const { - return xt_simd::select(v < lo, lo, xt_simd::select(hi < v, hi, v)); + return xt_simd::select(lo < hi, xt_simd::select(v < lo, lo, xt_simd::select(hi < v, hi, v)), hi); } }; diff --git a/test/test_xmath.cpp b/test/test_xmath.cpp index 8f56e93b9..57771859b 100644 --- a/test/test_xmath.cpp +++ b/test/test_xmath.cpp @@ -222,6 +222,15 @@ namespace xt EXPECT_EQ(res1, clip(opt_a, 2.0, 4.0)); } + TEST(xmath, clip_amin_greater_than_amax) + { + // NumPy-compatible behavior: when a_min > a_max, all values + // are set to a_max (the hi bound). + const xarray arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + const xarray expected = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + EXPECT_EQ(expected, clip(arr, 8, 1)); + } + TEST(xmath, sign) { shape_type shape = {3, 2};