Random Numbers in Scheme

Here’s the translation of the Go random numbers example to Scheme:

Our example demonstrates generating random numbers in Scheme. We’ll use the random procedure provided by most Scheme implementations for this purpose.

(import (scheme base)
        (scheme write))

;; Generate a random integer n, where 0 <= n < 100
(display (random 100))
(display ",")
(display (random 100))
(newline)

;; Generate a random float f, where 0.0 <= f < 1.0
(display (random 1.0))
(newline)

;; Generate random floats in the range 5.0 <= f < 10.0
(define (random-range min max)
  (+ min (* (random 1.0) (- max min))))

(display (random-range 5.0 10.0))
(display ",")
(display (random-range 5.0 10.0))
(newline)

;; Using a known seed for reproducible random numbers
(define (make-random-generator seed)
  (let ((a 1103515245)
        (c 12345)
        (m 2147483648))
    (lambda ()
      (set! seed (modulo (+ (* a seed) c) m))
      (/ seed m))))

(define rng1 (make-random-generator 42))
(define rng2 (make-random-generator 42))

(display (floor (* 100 (rng1))))
(display ",")
(display (floor (* 100 (rng1))))
(newline)

(display (floor (* 100 (rng2))))
(display ",")
(display (floor (* 100 (rng2))))
(newline)

In this Scheme example:

  1. We use the random procedure to generate random integers and floats. The exact behavior might vary between Scheme implementations, but generally:

    • (random n) where n is an integer returns a random integer between 0 (inclusive) and n (exclusive).
    • (random 1.0) returns a random float between 0.0 (inclusive) and 1.0 (exclusive).
  2. We define a random-range function to generate random floats within a specific range, similar to the Go example.

  3. To demonstrate seeded random number generation, we implement a simple linear congruential generator. This isn’t as sophisticated as Go’s PCG, but it serves to show how you might create reproducible random numbers in Scheme.

  4. We create two random number generators with the same seed to show that they produce the same sequence of numbers.

Note that the output may differ between runs and Scheme implementations:

68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Scheme doesn’t have a standard random number library as extensive as Go’s math/rand/v2. Different Scheme implementations might provide additional random number generation functions or more sophisticated algorithms. Always refer to your specific Scheme implementation’s documentation for the most accurate and comprehensive information on random number generation.