Park-Miller random number generator in Common Lisp

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

About these ads

One thought on “Park-Miller random number generator in Common Lisp

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s