Random Numbers in Clojure

Clojure provides random number generation through its clojure.core/rand and clojure.core/rand-int functions. For more advanced functionality, we can use the java.util.Random class from Java.

(ns random-numbers
  (:import (java.util Random)))

(defn main []
  ; For example, `rand-int` returns a random integer n,
  ; 0 <= n < 100.
  (print (rand-int 100) ",")
  (println (rand-int 100))

  ; `rand` returns a double f,
  ; 0.0 <= f < 1.0.
  (println (rand))

  ; This can be used to generate random doubles in
  ; other ranges, for example 5.0 <= f' < 10.0.
  (print (+ 5 (* (rand) 5)) ",")
  (println (+ 5 (* (rand) 5)))

  ; If you want a known seed, create a new
  ; Random object with a specific seed.
  (let [r2 (Random. 42)]
    (print (.nextInt r2 100) ",")
    (println (.nextInt r2 100)))

  ; Creating another Random object with the same seed
  ; will produce the same sequence of numbers.
  (let [r3 (Random. 42)]
    (print (.nextInt r3 100) ",")
    (println (.nextInt r3 100))))

(main)

To run the program, you can save it as random_numbers.clj and use the Clojure command-line tool:

$ clj random_numbers.clj
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

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

In this Clojure version:

  1. We use rand-int for generating random integers and rand for random doubles.
  2. To create a seeded random number generator, we use Java’s Random class.
  3. The PCG (Permuted Congruential Generator) is not directly available in Clojure, so we use Java’s Random class as an alternative.
  4. The syntax and function names are adapted to Clojure conventions.

See the Clojure documentation for references on other random quantities that Clojure can provide.