Skip to content

Pin last value to 1.0 in cumulative_distribution to address floating-point errors. - #8342

Merged
amcandio merged 4 commits into
networkx:mainfrom
tillahoffmann:cdf-rounding-error
Nov 12, 2025
Merged

amcandio merged 4 commits into
networkx:mainfrom
tillahoffmann:cdf-rounding-error

Conversation

@tillahoffmann

Copy link
Copy Markdown
Contributor

When parameters to cumulative_distribution are low-precision floats, e.g., from NumPy with dtype=np.float32, floating-point errors can accumulate. This leads to the last cdf value in cumulative_distribution being < 1.0, and the samples returned by discrete_sequence can be out-of-bounds. This PR makes a minimal change and fixes the last cdf value to 1.0, overcoming possible rounding errors.

Here's a snippet that fails before this change and passes afterwards.

import networkx as nx
import numpy as np


gamma = np.asarray(0.8586120009422302, dtype=np.float32)
num_nodes = 1000
seed = 15_158


graph = nx.gn_graph(num_nodes, lambda k: k**gamma, seed=seed)
assert nx.number_of_selfloops(graph) == 0, (
    f"Self loops in DIRECTED graph for seed {seed}: {list(nx.selfloop_edges(graph))}"
)

@amcandio

amcandio commented Nov 9, 2025

Copy link
Copy Markdown
Contributor

Thanks! Can you add the snippet as a unit test? Also, I think that instead of setting the last value to 1, it would be cleaner if we compute all the sums and then normalize in a second pass.

@tillahoffmann

Copy link
Copy Markdown
Contributor Author

Thanks for the fast review. I've added the renormalization and a seeded test that specifically targets the cumulative distribution evaluation. Thought bringing in the gn_graph might make the test a bit too complex.

@amcandio amcandio added type: Bug fix floating-point Issues that ultimate stem from numerical precision labels Nov 10, 2025
@amcandio

Copy link
Copy Markdown
Contributor

Thanks! The unit test was failing due to depending on numpy so I took the liberty of updating it with:

In [10]: nx.utils.cumulative_distribution([0.1] * 100)[-1]
Out[10]: 1.0000000000000007

@tillahoffmann

Copy link
Copy Markdown
Contributor Author

Thank you for the updates to the tests!

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No matter what is done here, accumulation of deviations from inexact types will be problematic. While the renormalization of the cdf looks better, it's just re-formulating how precision issues may crop up (in a less obvious way).

In practice I think the right answer is: folks should not be using this function externally; especially with inexact types. A quick look at internal usages shows that it is primarily used to represent cumulative degree distributions, so the elements are at least expected to be integers and accumulation of rounding errors isn't an issue.

@tillahoffmann in what context did you run into the usage of this function? Are you using it directly in your own code, or did the issues crop up from elsewhere in NetworkX?

@amcandio

Copy link
Copy Markdown
Contributor

I agree that floating point precision errors are unavoidable. But I'm still +1 on the PR because it fixes a fundamental property of cdf

@tillahoffmann

tillahoffmann commented Nov 11, 2025 •

Copy link
Copy Markdown
Contributor Author

I was using the gn_graph function to generate random graphs for simulation-based inference. We started seeing self-loops in the gn_graph realizations. That's because the bisect call in discrete_sequence has a small but non-zero probability to generate an out-of-bound sample. E.g., if the cdf is [0, 0.1, ..., 0.9999] then there's a 1e-4 chance of generating a sample outside the support of the distribution.

The numerical error is of course much smaller than 1e-4, but we've been generating on the order of 1e6 graphs with 1000 nodes each such that we occasionally run into these self-loops for kernels lambda degree: degree ** gamma for 32-bit precision exponents gamma.

I think doing the normalization at the end is nice because it guarantees there are no out-of-bound samples.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the background @tillahoffmann - +1 for putting this in on a "practicality beats purity" basis. I'd generally vote for warning about precision issues in the docstring, but the docstring is very minimal so let's not have it be a blocker. Thanks @tillahoffmann and @amcandio !

@amcandio
amcandio merged commit 5fa842b into networkx:main Nov 12, 2025
@amcandio

Copy link
Copy Markdown
Contributor

Thank you folks!

@dschult dschult added this to the 3.6 milestone Nov 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

floating-point Issues that ultimate stem from numerical precision type: Bug fix

Development

Successfully merging this pull request may close these issues.

4 participants