Skip to content

Commit 5fa842b

Browse files
Pin last value to 1.0 in cumulative_distribution to address floating-point errors. (#8342)
* Renormalize cdf after summation to improve numerical stability. * Removing numpy dependency from unit tests * Removing numpy dependency from unit tests * Adding missing assert to unit test --------- Co-authored-by: Alejandro Candioti <amcandio@gmail.com>
1 parent d302ea1 commit 5fa842b

2 files changed

Lines changed: 9 additions & 4 deletions

File tree

networkx/utils/random_sequence.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,11 @@ def cumulative_distribution(distribution):
131131
"""Returns normalized cumulative distribution from discrete distribution."""
132132

133133
cdf = [0.0]
134-
psum = sum(distribution)
135-
for i in range(len(distribution)):
136-
cdf.append(cdf[i] + distribution[i] / psum)
137-
return cdf
134+
cumulative = 0.0
135+
for element in distribution:
136+
cumulative += element
137+
cdf.append(cumulative)
138+
return [element / cumulative for element in cdf]
138139

139140

140141
@py_random_state(3)

networkx/utils/tests/test_random_sequence.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,7 @@ def test_random_weighted_choice():
4747
c = nx.utils.weighted_choice(mapping, seed=1)
4848
c = nx.utils.weighted_choice(mapping)
4949
assert c == "a"
50+
51+
52+
def test_random_sequence_low_precision():
53+
assert nx.utils.cumulative_distribution([0.1] * 100)[-1] == 1.0

0 commit comments

Comments
 (0)