Crate pyrand

Source
Expand description

Implements a 32-bit mersenne twister specifically aiming to be able to reproduce the results of python’s random module. Seeding this generator with the equivalent to a given python value will produce identical values.

This implementation is based on Python 3.13 and should be downwards compatible at least down to Python 3.4.

Function- and variable names as well as large parts of the implementation are strongly oriented on the CPython source. I also took some comments from there.

Note that while a rand implementation is given you shouldn’t expect most methods from rand::Rand to return the same values as their python counterparts.

§Examples

Choosing random values from a collection like

use pyrand::{PyMt19937, PySeedable, RandomChoiceIterator};
let rng = &mut PyMt19937::py_seed("Pizza");
assert_eq!((0..20).choose(rng).take(5).collect::<Vec<_>>(), vec![3, 3, 15, 2, 16]);

will return the same result as the equivalent python code

import random
rng = random.Random("Pizza")
rng.choices(range(20), k=5)

Structs§

Choices
MTState

Traits§

PySeedable
Trait for python-compatibly seedable Rngs
RandomChoiceIterator
Iterator extension trait to provide fluent interface for python choices

Type Aliases§

PyMt19937