Fast Random Number Generation
fastrand provides significantly faster random number generation in Python compared to the standard `random` module, implemented as a C extension. It is suitable for applications where speed is critical and cryptographic security is not required. The current version is 3.0.8, with a maintenance cadence of small patches and occasional feature additions.
Common errors
-
ModuleNotFoundError: No module named 'fastrand'
cause The fastrand library has not been installed in the current Python environment.fixRun `pip install fastrand` in your terminal to install the library. -
AttributeError: module 'fastrand' has no attribute 'randint'
cause Attempting to use a function name from Python's standard `random` module (`randint`) which does not exist in the `fastrand` API.fixUse `fastrand.pcg32bounded(N)` to get a random integer in the range [0, N-1]. -
TypeError: pcg32bounded() takes exactly one argument (0 given)
cause The `fastrand.pcg32bounded()` function requires a single argument, which is the upper bound (exclusive) for the random integer generation.fixProvide a positive integer argument to `pcg32bounded()`, e.g., `fastrand.pcg32bounded(100)` for numbers 0-99.
Warnings
- gotcha fastrand is NOT cryptographically secure. Do not use it for security-sensitive applications, such as generating passwords, cryptographic keys, or tokens. It uses the PCG (Permuted Congruential Generator) algorithm, which is fast but not designed for cryptographic strength.
- gotcha fastrand is not a drop-in replacement for Python's built-in `random` module. Its API uses different function names (e.g., `pcg32bounded` instead of `randint`, `randdouble` instead of `random()`) and does not support seeding or state management in the same way.
- deprecated The `fastrand.seed()` function was present in very early versions (e.g., v0.x) but is not part of the current public API. The PCG generator in fastrand is designed to be automatically seeded, typically from system entropy upon initialization. Attempting to seed it directly via a `seed()` function will fail.
Install
-
pip install fastrand
Imports
- fastrand
from fastrand import random
import fastrand
Quickstart
import fastrand
print("Random integer [0, 99]:", fastrand.pcg32bounded(100))
print("Random 32-bit unsigned int:", fastrand.pcg32())
print("Random double [0, 1):")
for _ in range(3):
print(f" {fastrand.randdouble():.6f}")