JavaScript Park-Miller Random Numbers

JavaScript is a very strange language in several regards. The built-in JavaScript random number generator is not seedable so you can’t get reproducible random numbers even when you want them (typically during development).

One of the oldest and best known RNG algorithms is sometimes called the Park-Miller algorithm, because of a really well-written article by Park and Miller even though they didn’t create the algorithm. I coded up a JavaScript implementation of a Park-Miller RNG that’s good enough for lightweight work.


One drawback of the JavaScript implementation is that it uses a global variable named seed, so you have to be careful not to use that name elsewhere. The implementation is very odd too, because it defines a function declaration that returns an anonymous function which in turn is assigned as a member to the existing Math object! Kind of crazy, but that’s JavaScript.



While experimenting with the Park-Miller RNG, I noticed some unusual behavior. First, for typical small seed values (1, 2, 3, etc.), the first generated number is very small. Second, the eight and ninth generated numbers are always very close to each other. A solution to this undesirable behavior is to burn away 20 or so initial generated values. I searched the Internet and couldn’t find much information on the undesirable behavior of the Park-Miller algorithm.

This entry was posted in Machine Learning. Bookmark the permalink.