How to resolve the algorithm Pseudo-random numbers/PCG32 step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Pseudo-random numbers/PCG32 step by step in the OCaml 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 OCaml programming language

Source code in the ocaml programming language

let (>>) = Int64.shift_right_logical

let int32_bound n x =
  Int64.(to_int ((mul (logand (of_int32 x) 0xffffffffL) (of_int n)) >> 32))

let int32_rotate_right x n =
  Int32.(logor (shift_left x (-n land 31)) (shift_right_logical x n))

let pcg32_next inc st =
  Int64.(add (mul st 0x5851f42d4c957f2dL) inc)

let pcg32_output st =
  int32_rotate_right
    (Int32.logxor (Int64.to_int32 (st >> 27)) (Int64.to_int32 (st >> 45)))
    (Int64.to_int (st >> 59))

let seq_pcg32 (st, f) =
  let rec repeat st () = Seq.Cons (pcg32_output st, repeat (f st)) in
  repeat (f st)

let pcg32 seed_st seed_sq =
  let inc = Int64.(add (succ seed_sq) seed_sq) in
  Int64.add seed_st inc, pcg32_next inc


let () =
  pcg32 42L 54L |> seq_pcg32 |> Seq.take 5
  |> Seq.iter (Printf.printf " %lu") |> print_newline

let () =
  pcg32 987654321L 1L |> seq_pcg32 |> Seq.map (int32_bound 5) |> Seq.take 100000
  |> Seq.fold_left (fun a n -> a.(n) <- succ a.(n); a) (Array.make 5 0)
  |> Array.iteri (Printf.printf "%u: %u\n")


  

You may also check:How to resolve the algorithm Pathological floating point problems step by step in the AWK programming language
You may also check:How to resolve the algorithm Happy numbers step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Mandelbrot set step by step in the Metapost programming language
You may also check:How to resolve the algorithm String append step by step in the EMal programming language
You may also check:How to resolve the algorithm Knapsack problem/Bounded step by step in the J programming language