Jim's
Tutorials

Spring 2012
course
navigation

Jim says

Also check out these references :

Random numbers And Floating Point Arithmetic

The first chapter of Volume 2 is about generating random numbers. I decided to implement one of them here.

The linear congruent method

The first section focused on the linear congruent method which defines a sequence in terms of four chosen values \(m, a, c,\) and \(X_0\). The sequence is defined as:
$$ X_{n+1} = (a X_n + c) \mod m, \hspace{50px} n \ge 0 $$
He suggests that for ease of computation \(m\) should be chosen to be the word-size of the computer. Since my implementation is in JavaScript, I've arbitrarily chosen my \(m\) to be \(2^{16}\) since it is similar to the sorts of numbers we would see in a real implementation but small enough to be simple. The book goes into great detail describing the number theory behind choosing good values for \(a\) and \(c\). Rather than get bogged down in this I've decided to make \(a\) and \(c\) user inputs for the purpose of this implementation. As for \(X_0\), I figured that the unix timestamp when this page loads (\(\mod m\) of course) would be a reasonable way to prevent my generator from being totally predictable.
Lastly I'm providing a max input so that the generator can be used to get random numbers in a range other than \(0\) — \(2^{16}\). The random number that is output is simply taken \(\mod max\).



new number visualize
I noticed that if \(c\) is even it causes problems..
I read through most of the random numbers section. I particularly found it interesting that a random algorithm DOESN'T lead to better random numbers and in fact the best algorithms were relatively straight forward. I found particularly interesting the \(X_n = (X_{n-24}+X_{n-55}) \mod m\) method on page 27.

Floating point arithmetic

I read through much of the section on arithmetic up through floating point arithmetic. I found the note about the Babylonians using base-60 kind of neat. The actual algorithms in the floating point arithmetic section were somewhat illuminating if rather straight-forward. It's nice to know what the 'e' in something like 1e6 stands for. There was an italicized "under construction" paragraph on page 246 that suggested that double precision floating point numbers are basically obsolete and the section would be replaced by other things. I'm kind of curious about the history of this which the paragraph doesn't go into detail about.