Repository navigation
Pin last value to 1.0 in cumulative_distribution to address floating-point errors. - #8342
Conversation
|
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. |
d061f97 to
5905cbc
Compare
|
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 |
|
Thanks! The unit test was failing due to depending on numpy so I took the liberty of updating it with: |
|
Thank you for the updates to the tests! |
rossbar
left a comment
There was a problem hiding this comment.
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?
|
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 |
|
I was using the 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 I think doing the normalization at the end is nice because it guarantees there are no out-of-bound samples. |
rossbar
left a comment
There was a problem hiding this comment.
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 !
|
Thank you folks! |
When parameters to
cumulative_distributionare low-precision floats, e.g., from NumPy withdtype=np.float32, floating-point errors can accumulate. This leads to the last cdf value incumulative_distributionbeing < 1.0, and the samples returned bydiscrete_sequencecan 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.