How to resolve the algorithm Pseudo-random numbers/PCG32 step by step in the Haskell programming language
How to resolve the algorithm Pseudo-random numbers/PCG32 step by step in the Haskell programming language
Table of Contents
Problem Statement
PCG32 has two unsigned 64-bit integers of internal state:
Values of sequence allow 2**63 different sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
Note that this an anamorphism – dual to catamorphism, and encoded in some languages as a general higher-order unfold
function, dual to fold
or reduce
.
numbers using the above.
are: 2707161783 2068313097 3122475824 2211639955 3215226955
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pseudo-random numbers/PCG32 step by step in the Haskell programming language
The provided code defines a type PCGen
and instances it as a random generator, providing the next
function (which generates a new value and a new random generator) and the split
function (which is not implemented in this case).
The PCGen
type holds two Word64
values, state
and inc
.
The mkPCGen
function creates a new PCGen
generator from an initial state
and a sequence
value.
The next
function generates a new random number and a new PCGen
generator from the current state
and inc
values.
The toFloat
function converts a Word64 value to a float in the range [0, 1)
.
The randoms'
function generates a list of random numbers from a given RandomGen
generator g.
Source code in the haskell programming language
import Data.Bits
import Data.Word
import System.Random
import Data.List
data PCGen = PCGen !Word64 !Word64
mkPCGen state sequence =
let
n = 6364136223846793005 :: Word64
inc = (sequence `shiftL` 1) .|. 1 :: Word64
in PCGen ((inc + state)*n + inc) inc
instance RandomGen PCGen where
next (PCGen state inc) =
let
n = 6364136223846793005 :: Word64
xs = fromIntegral $ ((state `shiftR` 18) `xor` state) `shiftR` 27 :: Word32
rot = fromIntegral $ state `shiftR` 59 :: Int
in (fromIntegral $ (xs `shiftR` rot) .|. (xs `shiftL` ((-rot) .&. 31))
, PCGen (state * n + inc) inc)
split _ = error "PCG32 is not splittable"
randoms' :: RandomGen g => g -> [Int]
randoms' g = unfoldr (pure . next) g
toFloat n = fromIntegral n / (2^32 - 1)
You may also check:How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Phix programming language
You may also check:How to resolve the algorithm Binary digits step by step in the Crystal programming language
You may also check:How to resolve the algorithm Singly-linked list/Element definition step by step in the C# programming language
You may also check:How to resolve the algorithm Exponentiation order step by step in the Python programming language
You may also check:How to resolve the algorithm AKS test for primes step by step in the Delphi programming language