diff --git a/Lib/statistics.py b/Lib/statistics.py index 01ca6c51dafcaf..d8df4e324704c5 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -1217,7 +1217,13 @@ def quantiles(data, *, n=4, method='exclusive'): j = i * m // n # rescale i to m/n j = 1 if j < 1 else ld-1 if j > ld-1 else j # clamp to 1 .. ld-1 delta = i*m - j*n # exact integer math - interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n + # When the endpoints are equal or delta is zero, avoid + # the interpolation formula which can be off by 1 ULP + # due to floating-point rounding + if (data[j - 1] == data[j]) or not delta: + interpolated = float(data[j - 1]) + else: + interpolated = (data[j - 1] * (n - delta) + data[j] * delta) / n result.append(interpolated) return result diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py index 677a87b51b9192..551d40ef8c402c 100644 --- a/Lib/test/test_statistics.py +++ b/Lib/test/test_statistics.py @@ -2652,6 +2652,24 @@ def test_equal_inputs(self): self.assertEqual(quantiles(data, method='inclusive'), [10.0, 10.0, 10.0]) + def test_monotonic_with_duplicate_floats(self): + quantiles = statistics.quantiles + for x in (3.141592653589793, # irrational-ish + 1/3, # repeating binary fraction + 0.1, # non-exact decimal + 2.0, # exact power of two + 1e300, # large magnitude + 1e-300, # small magnitude + float.fromhex('0x1.fffffffffffffp+1023'), # near max float + sys.float_info.min, # smallest normal + ): + for n in range(2, 20): + result = quantiles([x, x], n=n, method='exclusive') + self.assertEqual(result, sorted(result), + msg=f'x={x}, n={n}') + self.assertTrue(all(v == x for v in result), + msg=f'x={x}, n={n}') + def test_equal_sized_groups(self): quantiles = statistics.quantiles total = 10_000 diff --git a/Misc/NEWS.d/next/Library/2026-05-23-23-14-26.gh-issue-150318.Utah1I.rst b/Misc/NEWS.d/next/Library/2026-05-23-23-14-26.gh-issue-150318.Utah1I.rst new file mode 100644 index 00000000000000..6c0e2340132f7a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-23-23-14-26.gh-issue-150318.Utah1I.rst @@ -0,0 +1 @@ +Fix ``quantiles(method='exclusive')`` returning unsorted cut points for duplicate floats.