Random Numbers in OCaml

Here’s the translation of the Go random numbers example to OCaml, formatted in Markdown suitable for Hugo:

The Random module in OCaml’s standard library provides pseudorandom number generation.

open Random

let () =
  (* For example, Random.int returns a random int n,
     0 <= n < max_int *)
  Printf.printf "%d,%d\n" (Random.int 100) (Random.int 100);

  (* Random.float 1.0 returns a float f,
     0.0 <= f < 1.0 *)
  Printf.printf "%f\n" (Random.float 1.0);

  (* This can be used to generate random floats in
     other ranges, for example 5.0 <= f' < 10.0 *)
  Printf.printf "%f,%f\n" 
    ((Random.float 5.0) +. 5.0)
    ((Random.float 5.0) +. 5.0);

  (* If you want a known seed, use Random.init
     to initialize the generator *)
  Random.init 42;
  Printf.printf "%d,%d\n" (Random.int 100) (Random.int 100);

  (* Creating a new random number generator *)
  let r = Random.State.make [|42; 1024|] in
  Printf.printf "%d,%d\n" 
    (Random.State.int r 100)
    (Random.State.int r 100)

To run the program, save it as random_numbers.ml and use ocaml to execute it:

$ ocaml random_numbers.ml
68,56
0.809023
5.840125,6.937056
94,49
94,49

Some of the generated numbers may be different when you run the sample.

Note that OCaml’s Random module uses a different algorithm than Go’s math/rand/v2 package. OCaml uses a linear congruential generator, while Go uses a permuted congruential generator (PCG). This means that even with the same seed, the sequences of random numbers will be different between the two languages.

See the Random module documentation for references on other random quantities that OCaml can provide.