RandPCG
A random number generator using the PCG algorithm.
Documentation: https://hexdocs.pm/rand_pcg/
Installation
Add
rand_pcg
to your list of dependencies inmix.exs
:def deps do [{:rand_pcg, "~> 0.1.0"}] end
If you are using the GenServer option, ensure
rand_pcg
is started before your application:def application do [applications: [:rand_pcg]] end
Examples
GenServer Option
Ensure the service is running if not included as an application:
RandPCG.start_link
Get Some Random
# Random 32 bit integer
RandPCG.random()
# Random 32 bit based float
RandPCG.random(:float)
# n Random 32 bit integers
RandPCG.random(n)
# Random nth of an enumerable
list = [:a, :b, :c]
RandPCG.random(list)
# Random integer x where min <= x <= max
RandPCG.random(min, max)
# n random integers x where min <= x <= max
RandPCG.random(min, max, n)
Set State
state = %RandPCG.State{seed: 234532454323451, inc: 1}
RandPCG.state(state)
Note
The initial seed is based on :os.system_time(:micro_seconds)
Without running the GenServer
You will have to maintain your own state of the random number generator.
Random 32 bit Integer
state = RandPCG.gen_state()
random_int_32 = RandPCG.xsh_rr(state)
state = advance(state)
If you do not advance the state, you will receive the same random number.
Random Integer in a Range
state = RandPCG.gen_state()
min = 1
max = 10
random_1_10_inclusive = RandPCG.rand_int(min, max, state)
state = advance(state)
RandPCG.gen_state
initial seed is based on :os.system_time(:micro_seconds)