Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Standard Scheme does not provide a random number generator, and although most Scheme implementations provide one, they tend to differ in their details. If you want to write a portable Scheme program, it's easy to build your own random number generator; here's a method due to Knuth:</p> <pre><code>(define random (let ((a 69069) (c 1) (m (expt 2 32)) (seed 19380110)) (lambda new-seed (if (pair? new-seed) (set! seed (car new-seed)) (set! seed (modulo (+ (* seed a) c) m))) (/ seed m)))) </code></pre> <p>Calling <code>(random)</code> returns a random fraction between 0 (inclusive) and 1 (exclusive). The random fractions cycle with period <em>m</em>. Calling <code>(random seed)</code> resets the seed of the random number generator, so that two random sequences starting from the same seed will be identical; dates in the form YYYYMMDD make good seeds (that's Knuth's birthday above). If you want to flip a coin, say: <code>(if (&lt; (random) 1/2) 'heads 'tails)</code>.</p> <p>Sometimes you want a random integer over a range. The <code>randint</code> function shown below returns a random integer on the range <em>lo</em> (inclusive) to <em>hi</em> (exclusive); <em>lo</em> defaults to 0:</p> <pre><code>(define (randint . args) (cond ((= (length args) 1) (floor (* (random) (car args)))) ((= (length args) 2) (+ (car args) (floor (* (random) (- (cadr args) (car args)))))) (else (error 'randint "usage: (randint [lo] hi)")))) </code></pre> <p>Random numbers such as these are good enough for simple simulations, but beware they are not suitable for cryptographic applications. If you are interested, I have several random number generators, including some suitable for cryptographic applications, at <a href="http://programmingpraxis.com/contents/themes/#Random%20Number%20Generators" rel="nofollow">my blog</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload