Sitelet https://github.com/numpy/numpy/pull/31379/files
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion numpy/_core/src/npymath/npy_math_internal.h.src
Original file line number Diff line number Diff line change
Expand Up @@ -650,12 +650,21 @@ npy_lcm@c@(@type@ a, @type@ b)
*
* #type = (npy_int, npy_long, npy_longlong)*2#
* #c = (,l,ll)*2#
* #utype = (npy_uint, npy_ulong, npy_ulonglong)*2#
* #func=gcd*3,lcm*3#
*/
NPY_INPLACE @type@
npy_@func@@c@(@type@ a, @type@ b)
{
return npy_@func@u@c@(a < 0 ? -a : a, b < 0 ? -b : b);
/*
* Cast to unsigned to avoid overflow when negating minimum signed value.
* For negative values, cast to unsigned first, then apply negation in
* unsigned arithmetic to avoid undefined behavior.
* This ensures correct behavior across all architectures. #31359
*/
@utype@ a_abs = a < 0 ? (@utype@)(0) - (@utype@)a : (@utype@)a;
@utype@ b_abs = b < 0 ? (@utype@)(0) - (@utype@)b : (@utype@)b;
return (@type@)npy_@func@u@c@(a_abs, b_abs);
}
/**end repeat**/

Expand Down
12 changes: 8 additions & 4 deletions numpy/_core/tests/test_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -4160,13 +4160,17 @@ def test_lcm_overflow(self):
assert_equal(np.lcm(a, b), 10 * big)

def test_gcd_overflow(self):
for dtype in (np.int32, np.int64):
# verify that we don't overflow when taking abs(x)
# not relevant for lcm, where the result is unrepresentable anyway
a = dtype(np.iinfo(dtype).min) # negative power of two
# verify that we don't overflow when taking abs(x) for INT_MIN
# this was undefined behavior that manifested on s390x with GCC 11.5
for dtype in (np.int8, np.int16, np.int32, np.int64):
a = dtype(np.iinfo(dtype).min) # INT_MIN
q = -(a // 4)
# Test with INT_MIN as first argument
assert_equal(np.gcd(a, q * 3), q)
assert_equal(np.gcd(a, -q * 3), q)
# Test with INT_MIN as second argument
assert_equal(np.gcd(q * 3, a), q)
assert_equal(np.gcd(-q * 3, a), q)

def test_decimal(self):
from decimal import Decimal
Expand Down
Loading