module Random

Overview

Random provides an interface for random values generation, using a pseudo random number generator (PRNG).

Random.rand    # => 0.167595
Random.rand(5) # => 2

The above methods delegate to a Random instance.

r = Random.new
r.rand      # => 0.0372991
r.next_bool # => true
r.next_int  # => 2223112

This module also defines a global method #rand, which Array#sample and Array#shuffle delegates.

rand     # => 0.293829
rand(10) # => 8

An instance of each class that includes Random is a random number generator with its own state. Usually such RNGs can be initialized with a seed, which defines their initial state. It is guaranteed that after initializing two different instances with the same seed, and then executing the same calls on both of them, you will get the same results. This allows exactly reproducing the same seemingly random events by just keeping the seed.

It is possible to make a custom RNG by including Random and implementing next_u to return an unsigned number of a pre-determined type (usually UInt32). The numbers generated by your RNG must be uniformly distributed in the whole range of possible values for that type (e.g. 0u32..UInt32::MAX). This allows all other methods of Random to be based on this and still produce uniformly distributed results. Your Random class should also have a way to initialize it. For pseudo-random number generators that will usually be an integer seed, but there are no rigid requirements for the initialization.

The default PRNG is Random::PCG32 which has a good overall statistical distribution (low bias of generated numbers) and is fast for overall usages on different platforms, but isn't cryptographically secure. If a third party has access to some generated numbers, she may deduce incoming numbers, putting your application at risk.

It is recommended to use a secure source, such as Random::Secure, Random::ISAAC or ChaCha20 for anything that needs security, such as online games, identification tokens, salts, initializing a PRNG, ... These PRNG are slower but cryptographically secure, so a third party can't deduce incoming numbers.

Defined in:

extlib.cr

Instance Method Summary

Instance Method Detail

def rand(type : UInt128.class) : UInt128 #

Returns a random UInt128

rand(UInt128) # => {{values[0].id}}

[View source]