| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Linear congruential pseudo random generators for natural numbers |
| 5 |
-- /!\ NB: LCGs must not be used for cryptographic applications |
| 6 |
------------------------------------------------------------------------ |
| 7 |
|
| 8 |
{-# OPTIONS --cubical-compatible --safe #-} |
| 9 |
|
| 10 |
module Data.Nat.PseudoRandom.LCG where |
| 11 |
|
| 12 |
open import Data.Nat.Base |
| 13 |
open import Data.Nat.DivMod using (_%_) |
| 14 |
open import Data.List.Base using (List; []; _∷_) |
| 15 |
|
| 16 |
------------------------------------------------------------------------ |
| 17 |
-- Type and generator |
| 18 |
|
| 19 |
record Generator : Set where |
| 20 |
field multiplier : ℕ |
| 21 |
increment : ℕ |
| 22 |
modulus : ℕ |
| 23 |
.{{modulus≢0}} : NonZero modulus |
| 24 |
|
| 25 |
step : Generator → ℕ → ℕ |
| 26 |
step gen x = |
| 27 |
let open Generator gen in |
| 28 |
((multiplier * x + increment) % modulus) |
| 29 |
|
| 30 |
list : ℕ → Generator → ℕ → List ℕ |
| 31 |
list zero gen x = [] |
| 32 |
list (suc k) gen x = x ∷ list k gen (step gen x) |
| 33 |
|
| 34 |
------------------------------------------------------------------------ |
| 35 |
-- Examples of parameters |
| 36 |
-- Taken from https://en.wikipedia.org/wiki/Linear_congruential_generator |
| 37 |
|
| 38 |
-- /!\ As explained in that wikipedia entry, none of these are claimed |
| 39 |
-- to be good parameters. |
| 40 |
|
| 41 |
-- Note also that if you need your output to have good properties you |
| 42 |
-- may need to postprocess the stream of values to only use some of the |
| 43 |
-- bits of the output! |
| 44 |
|
| 45 |
glibc : Generator |
| 46 |
glibc = record |
| 47 |
{ multiplier = 1103515245 |
| 48 |
; increment = 12345 |
| 49 |
; modulus = 2 ^ 31 |
| 50 |
} |
| 51 |
|
| 52 |
random0 : Generator |
| 53 |
random0 = record |
| 54 |
{ multiplier = 8121 |
| 55 |
; increment = 28411 |
| 56 |
; modulus = 134456 |
| 57 |
} |