Skip to content

Commit d5ddad2

Browse files
committed
gh-154942: Refresh statistics.kde cache after data changes
1 parent afd10f0 commit d5ddad2

3 files changed

Lines changed: 22 additions & 9 deletions

File tree

Lib/statistics.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,24 +1060,27 @@ def cdf(x):
10601060

10611061
else:
10621062

1063-
sample = sorted(data)
1063+
data_snapshot = tuple(data)
1064+
sample = sorted(data_snapshot)
10641065
bandwidth = h * support
10651066

1067+
def refresh():
1068+
nonlocal n, data_snapshot, sample
1069+
updated_data = tuple(data)
1070+
if updated_data != data_snapshot:
1071+
data_snapshot = updated_data
1072+
sample = sorted(updated_data)
1073+
n = len(updated_data)
1074+
10661075
def pdf(x):
1067-
nonlocal n, sample
1068-
if len(data) != n:
1069-
sample = sorted(data)
1070-
n = len(data)
1076+
refresh()
10711077
i = bisect_left(sample, x - bandwidth)
10721078
j = bisect_right(sample, x + bandwidth)
10731079
supported = sample[i : j]
10741080
return sum(K((x - x_i) / h) for x_i in supported) / (n * h)
10751081

10761082
def cdf(x):
1077-
nonlocal n, sample
1078-
if len(data) != n:
1079-
sample = sorted(data)
1080-
n = len(data)
1083+
refresh()
10811084
i = bisect_left(sample, x - bandwidth)
10821085
j = bisect_right(sample, x + bandwidth)
10831086
supported = sample[i : j]

Lib/test/test_statistics.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2428,6 +2428,14 @@ def integrate(func, low, high, steps=10_000):
24282428
data.append(100)
24292429
self.assertGreater(f_hat(100), 0.0)
24302430

2431+
for cumulative in (False, True):
2432+
with self.subTest(cumulative=cumulative):
2433+
data = [1, 2, 3]
2434+
estimate = kde(data, 1.0, 'triangular', cumulative=cumulative)
2435+
data[0] = 5
2436+
expected = kde(data, 1.0, 'triangular', cumulative=cumulative)
2437+
self.assertEqual(estimate(1.5), expected(1.5))
2438+
24312439
def test_kde_kernel_specs(self):
24322440
# White-box test for the kernel formulas in isolation from
24332441
# their downstream use in kde() and kde_random()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`statistics.kde` with a bounded-support kernel to refresh its cached
2+
sample when the contents of the input data change without changing its length.

0 commit comments

Comments
 (0)