this post was submitted on 31 Aug 2026
24 points (96.2% liked)
Programming
28389 readers
362 users here now
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities !webdev@programming.dev
founded 3 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Be careful of off-by-one errors!
In the range 0-255 there are 256 values, so you need to test 256 % n, which in your example 256 % 3 = 1, so this would give a very slightly uneven distribution.
As to your main point, you're right, and I believe the standard procedure is to just roll the random variable again any time it falls outside the largest integer multiple of the desired output range.
The last point is a correct method if you're accepting the theoretical risk that it could run forever. In case of an uniform distribution on the original range the probabilities converge to an uniform distribution on the smaller range. For non-uniform distributions you also get a distribution where the new probabilities are scaled sums of the original probabilities.
In reality you should probably introduce a maximum number of rerolls. In that case you have your issue again but you can easily calculate error estimates to choose a good tradeoff limit for your purposes.
The probability of going for
prepeats without hitting the lower end of the range is((N - M) / N) ^ pwhereNis the size of the input range andMis the size of the largest integer multiple of the output range, which falls exponentially towards zero aspincreases, so the chance of the process not terminating is zero.With OP's example, with an input range of 256 and an output range of 202, this would mean the probability of making 10 unsuccessful attempts would be
(54/256) ^ 10 = 0.00000017or about 1 in 6 million. The probability of making 20 unsuccessful attempts would be 1 in 36 trillion, and so on.Thank you for the correction! I wrote the post in hurry that's why this mistake.