A set of numbered brass measuring tokens displayed on a dark wooden testing surface

Integer draws and ranges

The generation of an integer within a set numerical interval is one of the most widespread tasks in experimental modeling, randomized testing, and educational demonstrations. Yet the implementation details of mapping raw machine bits to an inclusive span [Min, Max] are frequently misunderstood, introducing systematic skew that invalidates statistical experiments.

The Discrete Uniform Model

When drawing a value from an integer interval bounded by a and b inclusive, the underlying theoretical model is the Discrete Uniform Distribution, denoted U{a, b}. The total count of eligible outcomes k is:

k = b - a + 1

For the generation to be mathematically sound, every integer x in the range must satisfy:

P(X = x) = 1 / k

The Modulo Bias Flaw in Software

A frequent shortcut in computer programs is taking raw random bytes and applying the modulo operator:

result = min + (raw_random_integer % k)

This method is inherently biased unless k divides evenly into the total number of states representable by the raw integer type (e.g., 232 for an unsigned 32-bit word). When 232 is not a multiple of k, the remainder values appear once more often than the higher values. Over large trials, this produces a measurable drift toward the lower segment of the range.

Comparison of Bounding Algorithms

Method Uniformity Computational Cost Typical Failure Mode
Naive Modulo (%) Flawed (Biased) Minimal (1 cycle) Over-represents lower outcomes on small spans
Floating Multiplication Slightly Distorted Low IEEE 754 precision limits compress upper bound
Rejection Sampling Exact (Unbiased) Variable (< 2 draws avg) None; discards trailing uneven zone

Rejection Sampling Explained

To achieve true uniformity, our workbench uses rejection sampling. Let M be the largest integer that k can divide evenly within the 32-bit space:

limit = 0xFFFFFFFF - (0xFFFFFFFF % k)

Any 32-bit random draw equal to or greater than limit is simply discarded, and a new raw value is extracted. Because the accepted domain is an exact multiple of k, every remainder from 0 to k - 1 possesses exactly the same number of pre-images. This preserves mathematical parity and protects researchers against subtle edge biases.

Inclusive vs. Exclusive Boundary Confusion

Another persistent error occurs in pedagogical settings where software libraries differ in boundary conventions. Python's random.randint(a, b) includes b, whereas JavaScript's standard pattern Math.floor(Math.random() * b) excludes b unless explicitly corrected. When translating statistical protocols between environments, analysts must document explicit bounds to avoid truncating extreme observations.

Return to the lead integer tool to verify your own bounded sets, or continue reading about sample extraction techniques.