Random Numbers in Racket

Here’s the translation of the Go code example to Racket, formatted in Markdown suitable for Hugo:

Our first example demonstrates generating random numbers in Racket. Here’s the full source code:

#lang racket

(require math/random)

(define (main)
  ; For example, `random` returns a random integer n,
  ; 0 <= n < 100.
  (printf "~a,~a\n" (random 100) (random 100))

  ; `random` with no arguments returns a float f,
  ; 0.0 <= f < 1.0.
  (printf "~a\n" (random))

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

  ; If you want a known seed, use `pseudo-random-generator`.
  ; Create a new generator and use it with `parameterize`.
  (define gen (make-pseudo-random-generator))
  (pseudo-random-generator-vector-set! gen #(42 1024 1))
  (parameterize ([current-pseudo-random-generator gen])
    (printf "~a,~a\n" (random 100) (random 100)))

  ; Using the same seed produces the same sequence.
  (define gen2 (make-pseudo-random-generator))
  (pseudo-random-generator-vector-set! gen2 #(42 1024 1))
  (parameterize ([current-pseudo-random-generator gen2])
    (printf "~a,~a\n" (random 100) (random 100))))

(main)

To run the program, save it as random-numbers.rkt and use racket:

$ racket random-numbers.rkt
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 Racket, the math/random library provides functions for generating random numbers. The random function is versatile and can generate both integers and floating-point numbers.

When you need a known seed for reproducibility, Racket uses pseudo-random-generator objects. You can create a new generator, set its state, and use it within a parameterize block to affect the behavior of random.

See the Racket Random Number Generation documentation for references on other random quantities that Racket can provide.