Crate rand_pcg

source ·
Expand description

The PCG random number generators.

This is a native Rust implementation of a small selection of PCG generators. The primary goal of this crate is simple, minimal, well-tested code; in other words it is explicitly not a goal to re-implement all of PCG.


This crate provides:

  • Pcg32 aka Lcg64Xsh32, officially known as pcg32, a general purpose RNG. This is a good choice on both 32-bit and 64-bit CPUs (for 32-bit output).
  • Pcg64 aka Lcg128Xsl64, officially known as pcg64, a general purpose RNG. This is a good choice on 64-bit CPUs.
  • Pcg64Mcg aka Mcg128Xsl64, officially known as pcg64_fast, a general purpose RNG using 128-bit multiplications. This has poor performance on 32-bit CPUs but is a good choice on 64-bit CPUs for both 32-bit and 64-bit output.

These generators are all deterministic and portable (see Reproducibility in the book), with testing against reference vectors.

§Seeding (construction)

Generators implement the SeedableRng trait. All methods are suitable for seeding. Some suggestions:

  1. Seed from an integer via seed_from_u64. This uses a hash function internally to yield a (typically) good seed from any input.
    let rng = Pcg64Mcg::seed_from_u64(1);
  2. With a fresh seed, direct from the OS (implies a syscall):
    let rng = Pcg64Mcg::from_os_rng();
  3. From a master generator. This could be rand::thread_rng (effectively a fresh seed without the need for a syscall on each usage) or a deterministic generator such as rand_chacha::ChaCha8Rng. Beware that should a weak master generator be used, correlations may be detectable between the outputs of its child generators.

See also Seeding RNGs in the book.


Generators implement RngCore, whose methods may be used directly to generate unbounded integer or byte values.

use rand_core::{SeedableRng, RngCore};
use rand_pcg::Pcg64Mcg;

let mut rng = Pcg64Mcg::seed_from_u64(0);
let x = rng.next_u64();
assert_eq!(x, 0x5603f242407deca2);

It is often more convenient to use the rand::Rng trait, which provides further functionality. See also the Random Values chapter in the book.



  • A PCG random number generator (XSH RR 64/32 (LCG) variant).
  • A PCG random number generator (CM DXSM 128/64 (LCG) variant).
  • A PCG random number generator (XSL RR 128/64 (LCG) variant).
  • A PCG random number generator (XSL 128/64 (MCG) variant).

Type Aliases§