Below is a Common Lisp implementation of the Minimum Standard Random Number Generator described by Park and Miller in 1988.

**Problem statement**

Read the problem statement here at Programming Praxis. Be warned that the blog post mixes up the values for *lo* and *hi*. It took me ages to figure out why my program wasn’t returning correct results. I finally got the correct formulas from the paper the post links to.

**Solution**

Programming Praxis talks about 3 different implementations but I just implemented the first two:

(defun get-msrn-naive (x n) (let ((a 16807) (m 2147483647)) (mod (* a ;Multiply either by x or recursive call (if (eq n 1) x (get-msrn-naive x (- n 1)))) m))) (defun get-next-msrn (x) (let ( (a 16807) (m 2147483647) (q 127773) (r 2836) ) (let ( (result (- (* a (mod x q)) (* r (floor (/ x q))) ) ) ) (if (<= result 0) (+ result m) result ) ) ) ) (defun get-msrn-schrage (x n) (if (eq n 1) (get-next-msrn x) (get-msrn-schrage (get-next-msrn x) (- n 1))))

It can also be viewed here on Github Gist.

**Sample use**

(get-msrn-schrage 1 10000)

1043618065

(get-msrn-schrage 1 5)

1144108930

(get-msrn-naive 1 5)

1144108930

Advertisements

valbonneconsultingWARNING: programming in Lisp has been linked to accelerated growth of facial hair 🙂 http://wp.me/p35rFe-38