How do I generate random in Scheme? Is there a special form or would I have to create a procedure? And if so, how do I do that? (I'm trying to create a procedure called random-choice that inputs two strategies and returns one at random.)
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:
(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))))
Calling (random)
returns a random fraction between 0 (inclusive) and 1 (exclusive). The random fractions cycle with period m. Calling (random seed)
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: (if (< (random) 1/2) 'heads 'tails)
.
Sometimes you want a random integer over a range. The randint
function shown below returns a random integer on the range lo (inclusive) to hi (exclusive); lo defaults to 0:
(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)"))))
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 my blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With