Tuesday, October 30, 2012

Random Thoughts

A friend of mine posted the picture below on Facebook recently. About as basic, and wrong, random number generator as one can get. But it brings home a point – computer generated random numbers are not really random. They are pseudo random. A close approximation of random but not totally random.


Like so many things though the random number generator algorithms are good enough for many things. They are not generally good enough for serious encryption but for a lot of simulations and games they work just fine.

Most of them also let you reproduce a set of pseudo random numbers. By that I mean one can run a program a number of times and get the same “random numbers” time and time again. This is very useful in debugging code. It’s hard to know what outputs are correct if you don’t know in advance what the inputs are. Once your program is fully tested, what ever t hat means to your project, you can start using different “seeds” to get difference results for each run of the program.

I’ve seen students get frustrated trying to debug a program when they don’t know what numbers are coming into their algorithms. More fun, for some definitions of fun, is when students forget to really randomize their program and other students figure out the list of numbers coming, the algorithm and start winning every turn of a game program. Great teaching opportunities either way.

Getting to a random number, pseudo random that is, can be a pretty complicated process. Paul Vick, who was on the the Visual Basic team at the time, posted a note about pseudo-random numbers and Visual Basic. Included in this post is a code example of one version of a random number algorithm written in Visual Basic.

It's not an algorithm for the timid and it involves some concepts that many students will not learn in a first course in programming. But I think it is useful even in those cases for students to get a feel for some of the complexities involved in the process.

No comments: