Unbiased RNG-to-Outcome Mapping: Rejection Sampling and Modulo Bias

A random number generator can deliver perfectly uniform bits, yet the game’s outcome selection can still be biased. The defect may appear in one deceptively small line of code: taking a random integer and applying % number_of_outcomes without checking the source range. When the number of possible source values is not divisible by the number of target outcomes, some targets receive more source values than others. That is modulo bias.

This is an engineering concern for game development because randomness, outcome mapping and payout mathematics are separate layers. The generator supplies values under its design assumptions. The mapper converts those values to discrete selections. The mathematical model defines the intended probabilities and awards. If any layer is incorrect, a trustworthy result cannot be inferred merely because another layer passed a statistical test.

The examples below deliberately use a tiny eight-bit source and six equal-probability outcomes, so the arithmetic is visible. Real game models can use weighted symbol tables, reel strips, multiple draws and more elaborate transformations. Unbiased bounded-integer selection is an underlying primitive; it does not by itself validate a complete game or certify compliance.

Photorealistic game-development workstation illustrating the engineering context for RNG testing
Photorealistic game-development workstation illustrating the engineering context for RNG testing

Uniform samples and bounded outcome sets

Suppose an RNG returns one uniformly distributed unsigned eight-bit value x in the range 0 through 255 inclusive. There are 256 equally likely values. The application needs one of six equally likely outcome indices, 0 through 5. If the source had 252 values, the simplest modulo mapping would assign exactly 42 values to each index. But 256 is not divisible by six.

The words uniform and independent refer to different guarantees. A marginally uniform stream emits each value with equal probability in an appropriate model; independence concerns relationships between successive outputs. A game can have a perfectly unbiased mapping of individual integers and still suffer from a poorly designed generator, correlated draws, inappropriate reseeding or misuse of the sampled values. For a validated product, examine the generator and mapping together.

An outcome set also needs a precise definition. Selecting an index from a six-element list is not necessarily the same as selecting six actual game awards. One symbol may trigger a bonus and another may enter a second-stage table. A mathematically accurate game model describes the probability of the terminal award across all dependent stages, not only the apparent uniformity of the first symbol.

An implementation should specify whether the range is inclusive or exclusive, which integer types hold boundaries, and whether selection occurs from a cryptographically suitable source for the product’s threat model. Many library functions already provide unbiased bounded integers. Prefer such a well-reviewed primitive over a hand-rolled function unless there is a documented engineering reason to implement it.

How modulo bias appears

The naive mapping is outcome = x % 6. With x from 0 to 255, the sequence repeats every six integers. Since 256 = 6 × 42 + 4, outcomes 0, 1, 2 and 3 each have 43 preimages, while outcomes 4 and 5 each have 42. Therefore, the probabilities are not identical:

Target index Naive count of eight-bit inputs Exact probability
0 43 43/256 ≈ 16.796875%
1 43 43/256 ≈ 16.796875%
2 43 43/256 ≈ 16.796875%
3 43 43/256 ≈ 16.796875%
4 42 42/256 = 16.40625%
5 42 42/256 = 16.40625%

Every index should have probability exactly one sixth, about 16.666667%. The difference between an overrepresented and underrepresented index is one source value out of 256, or 0.390625 percentage points. The imbalance looks small, but if the outcome groups have different monetary expectations, the bias alters theoretical return. For example, grouping the highest-award event in an underrepresented bucket can lower expected return relative to the intended six-way model. The size of that change depends on actual prizes and the whole game design.

Exact naive modulo counts for eight-bit inputs mapped to six target indices
Exact naive modulo counts for eight-bit inputs mapped to six target indices

Increasing the source width generally reduces relative modulo imbalance for a fixed small target count; it does not eliminate the underlying defect. In a security-sensitive or audited mapping, the correct answer is not “the bias is probably negligible.” The design should either prove that the intended mapping is exact or document an explicitly permitted approximation under the relevant mathematical and contractual rules.

Modulo bias is distinct from weighted mapping. A game may intentionally give different probabilities to six symbols because the paytable was designed that way. That can be correct if the weights are specified and implemented accurately. A bug arises when the implementation probabilities unintentionally differ from the defined weights. An audit should compare implemented masses to the approved model rather than assume all final symbols ought to be equally frequent.

Rejection sampling step by step

Rejection sampling removes the unequal tail before applying modulo. For the eight-bit example, choose the largest multiple of six no greater than 256: 6 × floor(256/6) = 252. Draw a uniform value. If it is 0 through 251, return x % 6; otherwise, discard that draw and sample again. Exactly 252 accepted values remain, and every target index has 42 preimages.

# Educational pseudocode for a uniform source returning integers 0..255.
# Production code should use an approved, reviewed bounded-RNG primitive.

def bounded_six(next_uniform_byte):
    while True:
        x = next_uniform_byte()   # uniform integer in [0, 255]
        if x < 252:
            return x % 6
        # x in {252, 253, 254, 255}: reject and draw again

The probability of acceptance is 252/256 = 98.4375%. The expected number of draws is 256/252 ≈ 1.015873. This is a useful efficiency calculation, but it assumes successive source draws have the needed distribution and independence properties. A fresh sample after rejection must be an independent draw according to the generator model; reusing the same rejected input in a deterministic loop would never terminate.

Rejection sampling removes the four-value tail before mapping to six equal outcomes
Rejection sampling removes the four-value tail before mapping to six equal outcomes

Here is a small set of test vectors for the example:

Input byte Action Result
0 Accept Index 0
5 Accept Index 5
6 Accept Index 0
251 Accept Index 5
252 Reject Draw again
255 Reject Draw again
255, then 7 Reject first, accept second Index 1

These vectors cover boundaries and modulo wrapping; they are not sufficient as the only statistical evidence. Importantly, the mapping is independent of the game’s payout table. A six-way unbiased index can feed six equally weighted symbols, six positions in a reel segment or the first stage of a more elaborate distribution. The interpretation belongs to the next layer.

A different method samples the minimum number of bits required for the target range. For six outcomes, three bits produce 0 through 7 and must reject 6 and 7. Acceptance is 6/8, or 75%. This is still correct but less efficient than the eight-bit example. In practice, primitives often choose an algorithm appropriate to the available generator word size and supported integer range.

Boundary handling and integer correctness

The arithmetic becomes more subtle for 32-bit or 64-bit words. A common specification is range = 2^w, limit = floor(range / n) × n, accept only x < limit, then return x % n. The mathematics is simple, but 2^w may not fit in a w-bit unsigned variable. Code that tries to represent the full source-cardinality as the maximum unsigned value is off by one. Integer promotion, signedness and overflow behavior must be explicit.

If an API provides random_integer(upper_exclusive=n), consult its documented uniformity contract and use it rather than assuming that it implements a naive modulo. Python’s secrets.randbelow(n), for example, is intended to return an integer in [0, n) using a suitable source. Code examples should not infer details of an API’s internal implementation unless the library documents them.

Mapping contract checks: source width, positive bound, threshold, redraw, and result range
Mapping contract checks: source width, positive bound, threshold, redraw, and result range

Defensive checks include n > 0, a defined maximum supported bound, a source range large enough to represent every possible target, correct handling of zero and the largest source integer, and a guarantee that the result is always less than n. If the bound can exceed the source-cardinality, combine sufficient independent bits into a larger integer or use a library primitive designed for arbitrary bounds; repeatedly drawing one eight-bit sample cannot select one of 1,000 indices.

Beware signed remainder behavior across languages. For example, % applied to negative signed integers can produce different-looking behavior depending on language semantics. It is safer to sample an unsigned nonnegative value with a documented range, then map. Converting a floating-point number in [0, 1) to an index using multiplication and truncation also requires analysis of mantissa precision, endpoint behavior and the source’s actual discrete distribution.

A low-level implementation should not inadvertently reveal sensitive generator state in diagnostics. If production draws are confidential under the security model, logs can retain authorized outcome references and hashes without recording raw random state, seeds or internal stream positions. Testing and replay use controlled fixtures outside production, as described in the deterministic-debugging companion article.

Test vectors and distribution checks

Exact enumeration is the strongest practical test for small finite source spaces. For the eight-bit example, iterate over all 256 values, count each mapped outcome, and inspect the reject set. For the naive % 6 method, that produces [43,43,43,43,42,42]. For accepted rejection-sampling inputs, the count vector is exactly [42,42,42,42,42,42]. No random seed or p-value is needed to establish these counts.

For larger word sizes, use proof-based reasoning and property tests at representative boundaries. Property tests should assert that accepted outputs are inside [0, n), every accepted source value is handled, all defined reject values trigger a redraw, and edge bounds such as n=1, powers of two and n near the supported maximum behave correctly. When a reference implementation is independent of production code, comparing both across randomized cases can expose arithmetic mistakes.

Exact comparison of biased modulo and balanced rejection-sampling counts
Exact comparison of biased modulo and balanced rejection-sampling counts

Statistical tests are still useful for the complete RNG-plus-mapper pipeline. A chi-square goodness-of-fit test can detect some distribution defects when the expected counts are large enough, but passing it does not prove cryptographic unpredictability, independence or correct business outcomes. Choose the sample size and hypotheses before inspecting results, account for multiple tests, and investigate failure patterns rather than merely resampling until a desirable p-value appears.

For weighted selection, create a reference table of probabilities that sum to one. A simple way to implement exact rational weights is to convert them into integers over a documented common denominator, sample an unbiased bounded index over the total weight, then select via cumulative intervals. If the weights were approved as floating-point values, define how they are quantized to an exact discrete representation. Rounding at multiple stages can be a more consequential error than a one-count modulo imbalance.

A certification-oriented evidence package typically includes the approved mathematical model, source definitions, range proofs, source code version, test vectors, statistical analysis, build identity and traceability from game configuration to mapping tables. The exact independent-testing and licensing requirements differ across markets and cannot be inferred from a generic programming article.

Implementation pitfalls and audit notes

The most common mapping mistakes are easy to list but hard to detect once hidden behind several layers of gameplay: using % n on a mismatched source range; declaring an inclusive upper bound but implementing an exclusive one; accidentally converting a full-word value through a signed integer; using a tiny or repeating source range; reshuffling a weighting table without updating its hash; or testing only the output indices while missing an upstream generator defect.

A second group of mistakes concerns state and lifecycle. A retry should never trigger a new production outcome for an already-committed round. If outcome generation commits and a response is lost, the response path must recover the same stored outcome. Rejection sampling rejects candidate random integers, not legitimate settled game rounds. The word “reject” appears in both contexts but has completely different business implications.

A third group concerns explanations. RTP, volatility and RNG quality are not interchangeable measurements. An unbiased mapper cannot guarantee the target RTP if paytables are wrong, and a game can display its theoretical RTP correctly while producing short-run results far from that expectation. The validation process should connect generator assumptions, mapping correctness, game math and final financial settlement without claiming that one test proves all four.

The engineering takeaway is precise: when mapping uniform integers into a bounded space, make the mapping provably uniform, defend all integer boundaries, use reviewed primitives and retain reproducible evidence. A random-looking game is not a substitute for the distribution that the approved model actually specifies.

References and further reading

The numeric examples are educational and do not describe the mathematical configuration of any commercial game.

Scroll to Top