Skip to content

Ensure Zipf always returns values in range - #57

Merged
vks merged 1 commit into
rust-random:masterfrom
mstoeckl:zipf-range
Jun 25, 2026
Merged

vks merged 1 commit into
rust-random:masterfrom
mstoeckl:zipf-range

Conversation

@mstoeckl

@mstoeckl mstoeckl commented May 13, 2026 •

Copy link
Copy Markdown
Contributor
  • Added a CHANGELOG.md entry

Summary

This updates the Zipf sampler to always produce values in the range [1,n].

Motivation

This should fix #54.

Details

Due to floating point error, it was possible for x to exceed n even with small values of n. Updating the calculations producing x to avoid that error entirely would probably require somewhat complicated biasing and rounding tricks, so it is easier to just clip the output at the end. I've explicitly updated x to be <= n.floor() instead of just <= n to ensure the output remains integral even if n is not; this is compatible with the documentation of the Zipf sampler and matches non-erroneous current behavior. Because the overflow only occurs rarely (when the random sample is close to 1) this should have negligible effect on the distribution.

@vks vks 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.

Looks good, thanks!

Comment thread src/zipf.rs
Comment on lines 206 to 224
#[test]
fn zipf_sample() {
let d = Zipf::new(10., 0.5).unwrap();
let mut rng = crate::test::rng(2);
for _ in 0..1000 {
let r = d.sample(&mut rng);
assert!(r >= 1.);
}
}

#[test]
fn zipf_sample_s_1() {
let d = Zipf::new(10., 1.).unwrap();
let mut rng = crate::test::rng(2);
for _ in 0..1000 {
let r = d.sample(&mut rng);
assert!(r >= 1.);
}
}

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.

Could you please add assert!(r <= 10.)?

I think it makes sense to test the same invariant here that is now part of the fuzzing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sure, I've added the check.

Due to floating point error, it was possible for `x` to exceed `n`
even with small values of `n`.
@vks
vks merged commit 392e007 into rust-random:master Jun 25, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Zipf distributions returns values larger than n for n = 1.0

2 participants