You are looking at historical revision 24349 of this page. It may differ significantly from its current revision.


Random numbers using the FreeBSD generator.


This egg provides a good-quality random number generator derived from FreeBSD's generator, which is also used in other operating systems such as Mac OS X. It provides 31 bits of precision.

It can be used as a drop-in replacement for random in the core extras unit. Core random uses rand(3) and has serious deficiencies on Mac OS X and elsewhere, and is little more than a toy on Windows and Solaris. To override the core generator, simply

(use random-bsd)

This egg does not try to detect or use any random number generator provided natively by your system.


Generating random numbers

[procedure] (random-integer N)

Return a random integer in the range 0 .. N-1, where N is a fixnum or a flonum.

Returns a fixnum or (when the result is outside of fixnum range) a flonum. On 32-bit systems this allows the full 31-bit generator precision and a range of 0 .. 2^52-1.

On a 64-bit system this is equivalent to random-fixnum, though currently a bit slower.

[procedure] (random-fixnum N)

Return a fixnum in the range 0 .. N-1, where N is an exact integer.

On a 32-bit system, the range is 0 .. 2^30-2.

On a 64-bit system, the range is 0 .. 2^62-2. Note that when N > 2^31, there will be gaps in the result due to the 31-bit generator precision.

[procedure] (random N)

Alias for random-fixnum. This allows you to override the core random with

(use random-bsd)
[procedure] (random-real)

Return a random floating-point number in the range 0.0 <= x < 1.0.

Currently only 31 bits of precision are returned, even though doubles provide 53 bit precision. Therefore there will be some (evenly-distributed) gaps in the range.

Randomizing the generator

[procedure] (randomize [seed])

Seed the generator with integer SEED. If seed is not provided or #f, the generator is seeded with a combination of the current time (seconds and milliseconds) and process ID.

(randomize) is automatically called at module load time so it is not normally necessary to call it again.

[procedure] (randomize/device)

Seed the generator with external entropy. Currently, random data is obtained by reading /dev/random and used to initialize the generator state. If /dev/random is not present, it falls back to seeding with the current time and PID. This is like calling srandomdev(3).

On some systems, reading from /dev/random will block if there is insufficient entropy in the pool.

About this egg


Jim Ursetto, Ursetto Consulting, Inc.

The random number generator is taken from FreeBSD.

Version history

Initial release


Copyright (c) 2011, Ursetto Consulting, Inc. MIT license. Full license details here.

random.c is Copyright (c) 1983, 1993 The Regents of the University of California.