Scheme random numbers
last modified November 25, 2026 Guile 3.0
Programs use random numbers for games, simulations, tests, and sampling.
The numbers come from a pseudo-random number generator: an
algorithm that produces a sequence that looks random but is fully
determined by its starting state. Guile's random procedure
and its companions are built in and need no module. The examples are run
with GNU Guile 3.0.7; outputs that depend on a random seed taken from the
system differ from run to run.
The random procedure
(random n) returns a number from 0 up to, but not including,
n. For an exact integer n the result is an exact
integer.
(define (roll-die) (+ 1 (random 6))) (display (random 10)) (newline) (display (random 1000000000000000000000)) (newline) (display (list (roll-die) (roll-die) (roll-die) (roll-die) (roll-die))) (newline) (define (coin) (if (zero? (random 2)) 'heads 'tails)) (display (map (lambda (i) (coin)) (iota 8))) (newline)
roll-die shifts the range 0–5 to 1–6. Bignums work
too, so random can return integers of any size.
coin chooses between two symbols. The program is run twice,
and both runs print the same numbers: Guile starts every program with the
same default random state, *random-state*. This makes
programs repeatable, but it is rarely what a game wants. The next section
shows how to change it.
$ guile dice.scm 3 837718311232582213201 (6 6 5 3 3) (tails tails heads tails heads tails heads tails) $ guile dice.scm 3 837718311232582213201 (6 6 5 3 3) (tails tails heads tails heads tails heads tails)
Random states and seeds
A random state holds the position of the generator. random
takes an optional state as its second argument; without it,
*random-state* is used. seed->random-state
creates a state from a seed, and random-state-from-platform
creates one from a source of randomness of the operating system.
(define (rolls n state) (map (lambda (i) (+ 1 (random 6 state))) (iota n))) (define fixed (seed->random-state 2026)) (display (rolls 10 fixed)) (newline) (define again (seed->random-state 2026)) (display (rolls 10 again)) (newline) (define other (seed->random-state 7)) (display (rolls 10 other)) (newline) (set! *random-state* (random-state-from-platform)) (display (map (lambda (i) (+ 1 (random 6))) (iota 10))) (newline)
Two states created from the same seed produce the same sequence, and a
different seed gives a different one. A fixed seed is useful for tests and
for repeatable simulations, so the rest of the article seeds most
programs. Assigning a state from random-state-from-platform
to *random-state* gives a different sequence in every run, so
the last line of the output will differ on your machine.
$ guile seeding.scm (3 5 6 5 6 1 5 3 6 2) (3 5 6 5 6 1 5 3 6 2) (3 1 1 3 2 1 1 1 6 5) (2 2 3 4 2 1 1 5 5 4)
Random floats and ranges
When the argument of random is inexact, the result is an
inexact number in the same half-open range. random:uniform
returns a float between 0 and 1.
(set! *random-state* (seed->random-state 11)) (display (random 1.0)) (newline) (display (random:uniform)) (newline) (display (random 2.5)) (newline) (define (random-between low high) (+ low (random (- high low)))) (define (random-in-range low high) (+ low (random (+ 1 (- high low))))) (display (map (lambda (i) (random-between 20.0 25.0)) (iota 3))) (newline) (display (map (lambda (i) (random-in-range -3 3)) (iota 12))) (newline)
The program starts by seeding *random-state*, so its output
is the same in every run. random-between shifts a float from
the range 0 to high - low; the upper bound is never reached.
random-in-range works with integers and includes both bounds,
which is why it adds 1 to the width of the range.
$ guile floats.scm 0.3560514255531554 0.5277455191779712 1.317748131589815 (21.898379140937813 23.108841521486106 20.463280756836408) (-1 0 -2 3 -2 -2 0 3 -2 0 1 -1)
A dice histogram
A uniform generator gives each outcome the same chance. Counting many rolls shows how close the counts come to the expected values, and summing two dice shows a distribution that is no longer flat.
(use-modules (ice-9 format))
(set! *random-state* (seed->random-state 2026))
(define (roll-die)
(+ 1 (random 6)))
(define (count-rolls n)
(let ((counts (make-vector 7 0)))
(do ((i 0 (+ i 1)))
((= i n) counts)
(let ((face (roll-die)))
(vector-set! counts face (+ 1 (vector-ref counts face)))))))
(define rolls 6000)
(define counts (count-rolls rolls))
(do ((face 1 (+ face 1)))
((> face 6))
(let ((n (vector-ref counts face)))
(format #t "~a ~4d ~a~%" face n
(make-string (quotient n 25) #\*))))
(define (sum-of-two)
(+ (roll-die) (roll-die)))
(define sums (make-vector 13 0))
(do ((i 0 (+ i 1)))
((= i rolls))
(let ((s (sum-of-two)))
(vector-set! sums s (+ 1 (vector-ref sums s)))))
(do ((s 2 (+ s 1)))
((> s 12))
(format #t "~2d ~a~%" s
(make-string (quotient (vector-ref sums s) 25) #\*)))
The counts are kept in a vector indexed by the face, so index 0 is unused.
Each face is expected 1,000 times in 6,000 rolls, and the counts stay
close to that. A star stands for 25 rolls. The sum of two dice is not
uniform: there are six ways to roll a 7 and only one way to roll a 2 or a
12, so the bars form a triangle. ~4d and ~2d
from (ice-9 format) align the numbers.
$ guile histogram.scm 1 982 *************************************** 2 954 ************************************** 3 1019 **************************************** 4 1017 **************************************** 5 1029 ***************************************** 6 999 *************************************** 2 ****** 3 ************** 4 ******************* 5 ************************** 6 ********************************** 7 **************************************** 8 ******************************* 9 ************************** 10 ******************** 11 ************* 12 ******
Shuffling and sampling
A random element of a list needs a random index. A random permutation needs more care: the Fisher–Yates algorithm swaps each element, from the last down, with a randomly chosen element at or before it, which gives every order the same probability.
(set! *random-state* (seed->random-state 5))
(define (random-element lst)
(list-ref lst (random (length lst))))
(define (swap! vec i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define (shuffle! vec)
(do ((i (- (vector-length vec) 1) (- i 1)))
((< i 1) vec)
(swap! vec i (random (+ i 1)))))
(define (shuffle lst)
(vector->list (shuffle! (list->vector lst))))
(define (sample lst k)
(list-head (shuffle lst) k))
(define colours '(red green blue yellow purple))
(display (random-element colours))
(newline)
(display (shuffle (iota 10 1)))
(newline)
(display (shuffle (iota 10 1)))
(newline)
(define suits '("S" "H" "D" "C"))
(define ranks '("A" "2" "3" "4" "5" "6" "7" "8" "9" "10" "J" "Q" "K"))
(define deck
(apply append
(map (lambda (s) (map (lambda (r) (string-append r s)) ranks))
suits)))
(display (length deck))
(newline)
(display (sample deck 5))
(newline)
(display (sort (sample (iota 49 1) 6) <))
(newline)
shuffle! works in place on a vector, as described in the
vectors article, and shuffle
converts a list to a vector and back. sample takes the first
k elements of a shuffled list, so no element is chosen twice.
The deck has 52 cards built with nested map, and a lottery
draws six numbers out of 49 and sorts them with sort from the
sorting article.
$ guile shuffle.scm blue (5 2 9 3 10 1 7 6 8 4) (2 5 3 6 8 10 7 4 9 1) 52 (8S 7S 9S 2D AH) (3 4 12 22 41 47)
Normal and exponential distributions
Many quantities cluster around an average. random:normal
returns a number from the normal distribution with mean 0 and standard
deviation 1, and random:exp one from the exponential
distribution with mean 1, which models waiting times.
(use-modules (ice-9 format))
(set! *random-state* (seed->random-state 42))
(define (normal mean sd)
(+ mean (* sd (random:normal))))
(define (average xs)
(/ (apply + xs) (length xs)))
(define (std-dev xs)
(let ((m (average xs)))
(sqrt (average (map (lambda (x) (* (- x m) (- x m))) xs)))))
(define heights (map (lambda (i) (normal 175.0 7.0)) (iota 5000)))
(format #t "mean ~,2f, standard deviation ~,2f~%"
(average heights) (std-dev heights))
(define (bucket h)
(* 5 (inexact->exact (floor (/ h 5)))))
(define counts (make-hash-table))
(for-each (lambda (h)
(hash-set! counts (bucket h) (+ 1 (hash-ref counts (bucket h) 0))))
heights)
(for-each
(lambda (b)
(let ((n (hash-ref counts b)))
(format #t "~a-~a ~4d ~a~%" b (+ b 4) n
(make-string (quotient (+ n 24) 25) #\*))))
(sort (hash-map->list (lambda (key value) key) counts) <))
(define waits (map (lambda (i) (* 3.0 (random:exp))) (iota 5000)))
(format #t "average wait ~,2f min, longest ~,2f min~%"
(average waits) (apply max waits))
normal scales and shifts the standard normal value, here to
heights with mean 175 cm and standard deviation 7 cm. The computed mean and
deviation of 5,000 samples are close to these parameters. The heights are
counted in buckets of 5 cm in a hash
table, and the keys are sorted before printing; a star stands for up
to 25 people, so even a single value gets one. The histogram has the bell
shape of the normal distribution. Scaling random:exp by 3
models waits with an average of three minutes; most waits are short, but
a few are much longer.
$ guile normal.scm mean 174.83, standard deviation 6.93 150-154 12 * 155-159 62 *** 160-164 308 ************* 165-169 855 *********************************** 170-174 1331 ****************************************************** 175-179 1312 ***************************************************** 180-184 767 ******************************* 185-189 269 *********** 190-194 70 *** 195-199 13 * 200-204 1 * average wait 2.94 min, longest 23.09 min
Estimating pi
A Monte Carlo method estimates a value from random samples. Points chosen uniformly in a unit square fall inside the quarter circle of radius 1 with probability π/4, so four times the share of hits estimates π.
(use-modules (ice-9 format))
(set! *random-state* (seed->random-state 314))
(define (inside-circle?)
(let ((x (random 1.0))
(y (random 1.0)))
(<= (+ (* x x) (* y y)) 1.0)))
(define (estimate-pi n)
(let loop ((i 0) (hits 0))
(if (= i n)
(* 4.0 (/ hits n))
(loop (+ i 1) (if (inside-circle?) (+ hits 1) hits)))))
(for-each
(lambda (n)
(let ((est (estimate-pi n)))
(format #t "~8d ~,6f error ~,6f~%" n est (abs (- est 3.141592653589793)))))
'(100 1000 10000 100000 1000000))
inside-circle? picks a point and tests its distance from the
origin. The named let counts the hits without building a
list. The error shrinks as the number of points grows, but slowly and not
steadily: in this run 1,000 points beat 10,000, 100,000 points beat a
million, and a million points still give only two correct decimals.
$ guile monte-carlo.scm
100 2.640000 error 0.501593
1000 3.156000 error 0.014407
10000 3.117600 error 0.023993
100000 3.140480 error 0.001113
1000000 3.143260 error 0.001667
The birthday problem
Simulation can also answer questions that are hard to work out by hand. The birthday problem asks how likely it is that at least two people in a group share a birthday.
(use-modules (ice-9 format))
(set! *random-state* (seed->random-state 365))
(define (same-birthday? people)
(let ((seen (make-vector 365 #f)))
(let loop ((i 0))
(cond ((= i people) #f)
(else
(let ((day (random 365)))
(if (vector-ref seen day)
#t
(begin (vector-set! seen day #t)
(loop (+ i 1))))))))))
(define (probability people trials)
(let loop ((i 0) (hits 0))
(if (= i trials)
(exact->inexact (/ hits trials))
(loop (+ i 1) (if (same-birthday? people) (+ hits 1) hits)))))
(for-each
(lambda (people)
(format #t "~2d people: ~,3f~%" people (probability people 20000)))
'(10 23 40 60))
same-birthday? draws birthdays for a group, ignoring leap
years, and marks each day in a vector; it stops as soon as a day comes up
twice. probability repeats the experiment 20,000 times. With
23 people the chance is already about one half, which surprises most
people, and with 60 people a shared birthday is almost certain.
$ guile birthday.scm 10 people: 0.117 23 people: 0.506 40 people: 0.894 60 people: 0.995
Random passwords
The last example generates passwords that contain at least one lower case letter, one upper case letter, one digit, and one symbol. It seeds the generator from the platform, so each run prints different passwords.
(set! *random-state* (random-state-from-platform))
(define lower "abcdefghijklmnopqrstuvwxyz")
(define upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
(define digits "0123456789")
(define symbols "!#$%&*+-=?@")
(define (random-char str)
(string-ref str (random (string-length str))))
(define (shuffle-string str)
(let ((vec (list->vector (string->list str))))
(do ((i (- (vector-length vec) 1) (- i 1)))
((< i 1) (list->string (vector->list vec)))
(let* ((j (random (+ i 1)))
(tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))))
(define (password len)
(let ((all (string-append lower upper digits symbols)))
(shuffle-string
(string-append
(string (random-char lower) (random-char upper)
(random-char digits) (random-char symbols))
(list->string
(map (lambda (i) (random-char all)) (iota (- len 4))))))))
(define (hex-token bytes)
(string-pad (number->string (random (expt 256 bytes)) 16)
(* 2 bytes) #\0))
(for-each (lambda (len) (display (password len)) (newline)) '(8 12 16))
(display (hex-token 16))
(newline)
random-char picks a character from a string. The password
starts with one character of each kind, is filled up with characters from
all groups, and is shuffled so that the required characters are not
always at the start. hex-token draws a number of 128 bits and
pads its hexadecimal form with zeros to 32 digits. Guile's generator is
not designed for cryptography; real secrets should be read from a
cryptographic source such as /dev/urandom, for example with
the binary ports of the files article.
$ guile passwords.scm W+w#1mGh 1CEHJdx1*5e! d44fhqYPY2@Z-JSJ d25fefc22a7c2ed4ea8f67b322ddab7a
Source
Random Number Generation — GNU Guile Reference Manual
In this article we have generated random integers and floats, seen why Guile repeats the same sequence by default, created reproducible states from seeds and fresh states from the platform, generated numbers in a range, counted dice rolls, shuffled and sampled lists, drawn from the normal and exponential distributions, estimated π and solved the birthday problem by simulation, and generated passwords. The numbers article explains exact and inexact numbers, and the vectors article the vector procedures used here.
Author
List all Scheme tutorials.