Skip to content
Open
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
8 changes: 7 additions & 1 deletion Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix ``quantiles(method='exclusive')`` returning unsorted cut points for duplicate floats.
Loading