Common RNG Mistakes: Modulo Bias, Seeding Pitfalls, and Range Bugs
Random number generation (RNG) powers simulations, games, and security. Small mistakes create big problems—skewed odds, predictable outputs, or brittle tests. Here’s what to avoid and how to fix it.
1) Modulo Bias
- Problem: x % nis biased when the RNG’s native range isn’t a multiple ofn—some outcomes occur more often.
- Fix: Use rejection sampling or a library function that returns uniform integers within a range.
2) Predictable Seeding
- Problem: Seeding with the current time makes sequences guessable.
- Fix:
- For reproducible science/tests: fixed, documented seeds.
- For games/simulations where uniqueness matters: combine time with additional entropy.
- For security: use a cryptographically secure RNG (CSPRNG), not a PRNG with a custom seed.
 
3) Off‑By‑One Range Errors
- Problem: Confusing inclusive vs. exclusive bounds (e.g., 0..n vs. 0..n‑1) produces out‑of‑range values or missing endpoints.
- Fix: Centralize range helpers, assert bounds in tests, document conventions (inclusive/exclusive).
4) Assuming Independence Where None Exists
- Problem: Transformations can correlate outputs (e.g., shuffling with a biased method).
- Fix: Use proven algorithms (Fisher–Yates for shuffles), and validate with tests.
5) Too Few Samples in Tests
- Problem: Tiny samples pass by luck or fail spuriously.
- Fix: Use thousands of draws for distribution checks; apply chi‑square/KS tests where appropriate.
6) Using PRNGs for Security Tasks
- Problem: Non‑cryptographic PRNGs leak patterns; seeds can be inferred.
- Fix: Use OS CSPRNGs or vetted crypto libraries for keys, tokens, and passwords.
Quick Checklist
- Uniform range without modulo bias
- Clear inclusive/exclusive semantics
- Seed policy: reproducible vs. unpredictable
- Stat tests on large samples when correctness matters
FAQs
Why is modulo bias bad?
If the RNG range (e.g., 2^32) isn’t divisible by your target n, some residues occur more frequently, skewing outcomes.
Related Articles
