scheme shell
about
download
support
resources
docu
links
 
scsh.net

Thirty Two Bit Random Integers

Fast generator for pseudo-random 32-bit integers

This is the "fast" linear congruential pseudo-random number generator `ranqd1' from chapter 7 of Numerical Recipes. Note that because Scheme systems generally offer native support for "big" integers, one has to use `modulo' in the Scheme code to emulate the behavior of 32-bit Fortran and C systems.

See http://lib-www.lanl.gov/numerical/bookfpdf/f7-1.pdf for details.

Note that this is a very old, and very very poor, pseudo-random number generator. You should not use the code described on this page for any serious purpose, such as a Monte-Carlo simulation. Under Linux /dev/urandom (see RandomIntegerFromDevURandom for details) is an excellent source for good random numbers. You might also want to check the random() library function of the standard C library.

This code is also available from http://www.scsh.net/contrib/emilio.lopes/scheme.html.

-ECL

The Code

   (define (gen-ranqd1 seed)
     (let ((random seed)
           (2**32 #x100000000))
       (lambda ()
         (set! random (modulo (+ (* random 1664525) 1013904223) 2**32))
         random)))

Testing

You can use the following code to test `ranqd1' with your Scheme implementation:

   (let ((random (gen-ranqd1 0))
         (expected-results '(#x3c6ef35f
                             #x47502932
                             #xd1ccf6e9
                             #xaaf95334
                             #x6252e503
                             #x9f2ec686
                             #x57fe6c2d
                             #xa3d95fa8
                             #x81fdbee7
                             #x94f0af1a
                             #xcbf633b1)))
     (for-each (lambda (expected)
                 (let ((rnd (random)))
                   (if (not (= rnd expected))
                       (error (format #f "FAILED: expected ~a, got ~a" expected rnd)))))
               expected-results))

More on Random Numbers

SRFI-27 (http://srfi.schemers.org/srfi-27/) by Sebastian Egner specifies an interface to sources of random bits. There is also a workshop on a portable random number generator in Scheme (http://www.math.grin.edu/~stone/events/scheme-workshop/random.html) by John David Stone.


ThirtyTwoBitRandomIntegers - raw wiki source | code snippets archive