TWiki . Cookbook . ThirtyTwoBitRandomIntegers

Generating simple 32-bit random integers in portable Scheme

Problem

You want to generate pseudo-random integers in the range [0,2**32].

Solution

The following is a simple, portable (R5RS) generator of pseudo-random integers in Scheme. Chapter 7 of Numerical Recipes presents it as the "fast" linear congruential pseudo-random number generator (`ranqd1'). Please read the description of the algorithm and learn about its limitations before using this routine for any serious purpose.

Here is the code:

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

You can use the following to test it 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))


Comments about this recipe

Contributors

-- EmilioLopes - 11 Feb 2006

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 999

----- Revision r1.1 - 11 Feb 2006 - 17:04 GMT - EmilioLopes
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.