GeezerVison is showing github.com — Merge pull request #31379 from charris/backport-31360 · numpy/numpy@467eef5
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: numpy/_core/src/npymath/npy_math_internal.h.src +10-1Lines changed: 10 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -650,12 +650,21 @@ npy_lcm@c@(@type@ a, @type@ b) | 650 | 650 | * | 651 | 651 | * #type = (npy_int, npy_long, npy_longlong)*2# | 652 | 652 | * #c = (,l,ll)*2# | | 653 | + * #utype = (npy_uint, npy_ulong, npy_ulonglong)*2# | 653 | 654 | * #func=gcd*3,lcm*3# | 654 | 655 | */ | 655 | 656 | NPY_INPLACE @type@ | 656 | 657 | npy_@func@@c@(@type@ a, @type@ b) | 657 | 658 | { | 658 | | - return npy_@func@u@c@(a < 0 ? -a : a, b < 0 ? -b : b); | | 659 | + /* | | 660 | + * Cast to unsigned to avoid overflow when negating minimum signed value. | | 661 | + * For negative values, cast to unsigned first, then apply negation in | | 662 | + * unsigned arithmetic to avoid undefined behavior. | | 663 | + * This ensures correct behavior across all architectures. #31359 | | 664 | + */ | | 665 | + @utype@ a_abs = a < 0 ? (@utype@)(0) - (@utype@)a : (@utype@)a; | | 666 | + @utype@ b_abs = b < 0 ? (@utype@)(0) - (@utype@)b : (@utype@)b; | | 667 | + return (@type@)npy_@func@u@c@(a_abs, b_abs); | 659 | 668 | } | 660 | 669 | /**end repeat**/ | 661 | 670 |
| |
Collapse file Copy file name to clipboardExpand all lines: numpy/_core/tests/test_umath.py +8-4Lines changed: 8 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4160,13 +4160,17 @@ def test_lcm_overflow(self): | 4160 | 4160 | assert_equal(np.lcm(a, b), 10 * big) | 4161 | 4161 |
| 4162 | 4162 | def test_gcd_overflow(self): | 4163 | | - for dtype in (np.int32, np.int64): | 4164 | | - # verify that we don't overflow when taking abs(x) | 4165 | | - # not relevant for lcm, where the result is unrepresentable anyway | 4166 | | - a = dtype(np.iinfo(dtype).min) # negative power of two | | 4163 | + # verify that we don't overflow when taking abs(x) for INT_MIN | | 4164 | + # this was undefined behavior that manifested on s390x with GCC 11.5 | | 4165 | + for dtype in (np.int8, np.int16, np.int32, np.int64): | | 4166 | + a = dtype(np.iinfo(dtype).min) # INT_MIN | 4167 | 4167 | q = -(a // 4) | | 4168 | + # Test with INT_MIN as first argument | 4168 | 4169 | assert_equal(np.gcd(a, q * 3), q) | 4169 | 4170 | assert_equal(np.gcd(a, -q * 3), q) | | 4171 | + # Test with INT_MIN as second argument | | 4172 | + assert_equal(np.gcd(q * 3, a), q) | | 4173 | + assert_equal(np.gcd(-q * 3, a), q) | 4170 | 4174 |
| 4171 | 4175 | def test_decimal(self): | 4172 | 4176 | from decimal import Decimal | |
|