Fix handling of zero probability values in Gen.weighted #3544
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Gen.weighted can't currently handle generators with zero weight because it builds a map from the the cumulative probability to the generator, but a probability of zero doesn't change the cumulative probability, overwriting the initial value for that probability.
For example, when making a map of
(Gen.const(true), 1), (Gen.const(false), 0), firsttruegets added to the map, yieldingMap(1 -> Gen.const(true). Thenfalsegets added, resulting inMap(1 -> Gen.const(true), (1 + 0) -> Gen.const(false)). Sofalseoverwrites the earlier value, since adding zero doesn't change the probability.The first commit creates a failing test, the second one adds a fix. The fix also works when the added double isn't zero, but is so small that the cumulative probability wouldn't change, which can (in theory) happen, since doubles are not indefinitely precise (and have their precision distributed unevenly). For example,
weighted(("a", 100000000000.0), ("b", 0.000007))now drops "b" completely instead of overwriting "a", even though "b" doesn't have zero probability.It can (again, in theory) still fail when the values don't add up to exactly one.
I've also added a small example to the documentation of
weighted.