gleam_stats/generators

A module with all the necessary base-functions for generating random numbers. Some of the functions listed in the following are able to create a base-iterator that yields pseudo-random integer numbers. A base-iterator can then used with other functions to generate random numbers from common distributions. See the gleam_stats/distributions modules for this functionality.


Constants

pub const mask_32: Int = 4294967295

The value is equal to float.round(float.power(2., 32.)) - 1, which is the maximum value for a 32-bit unsigned integer.

pub const mask_64: Int = 18446744073709551615

The value is equal to float.round(float.power(2., 64.)) - 1, which is the maximum value for a 64-bit unsigned integer.

Functions

pub fn seed_lcg32(seed: Int) -> Iterator(Int)

Create a base-iterator that uses the Linear Congruential Generator (LCG32) algorithm to generate random numbers. The LCG32 algorithm is a generator of 32-bit random numbers and uses a 32-bit integer seed.

Example:
 import gleam/iterator.{Iterator}
 import gleam_stats/generators

 pub fn example () {
   let seed: Int = 5
   let stream: Iterator(Int) = generators.seed_lcg32(seed)
 }
pub fn seed_pcg32(seed: Int, seq: Int) -> Iterator(Int)

The function creates a base-iterator that uses the Permuted Congruential Generator (PCG32) algorithm to generate random integer numbers. The PCG32 algorithm is a generator of 32-bit random numbers and uses two 64-bit integer seeds (internal initial state and sequence/stream number). The PCG32 algorithm is fast, space effecient, and have good statitical properties.

Example:
 import gleam/iterator.{Iterator}
 import gleam_stats/generators

 pub fn example () {
   // 'seed' is the "current state" of the generator
   // It can be any 64-bit value.
   let seed: Int = 5
   // 'seed_sequence' defines which of the 2^63 possible
   // random sequences the current state is iterating through
   // It can be any 64-bit value.
   let seed_sequence: Int = 5
   let stream: Iterator(Int) = generators.seed_pcg32(seed, seed_sequence)
 }
pub fn take_randints(stream: Iterator(Int), m: Int) -> Result(
  #(List(Int), Iterator(Int)),
  String,
)

Take out ‘m’ integers from the raw stream of pseudo-random numbers produced by a base-iterator.

Example:
 import gleam/iterator.{Iterator}
 import gleam_stats/generators

 pub fn example() {
   let seed: Int = 5
   let seed_sequence: Int = 5
   assert Ok(out) =
     generators.seed_pcg32(seed, seed_sequence)
     |> generators.take_randints(5_000)
   let randints: List(Int) = pair.first(out)
   let stream: Iterator(Int) = pair.second(out)
 }
pub fn uint32(n: Int) -> Int

Gleam does not have 32 bit unsigned integers (integers are arbitrary-sized) so use an explicit bit mask to convert integers to 32 bit integers.

pub fn uint64(n: Int) -> Int

Gleam does not have 64 bit unsigned integers (integers are arbitrary-sized) so use an explicit bit mask to convert integers to 64 bit integers.