Friday, November 6, 2009

Terrible idea for generating random numbers

The Operating Systems course I am taking has just finished going over threading and concurrency, and it introduced me to multiplexing and thread scheduling. For whatever reason, I was thinking about random number generation the other day, and I thought: what if random numbers could be produced by making use of the nondeterminism of thread concurrency?

My idea:

To produce a random integer from 1 to N, create one global variable and run N threads in parallel. Each thread has a unique ID number ranging from 1 to N, and at each iteration of the thread's while loop, it tries to write its ID number to the global variable. In this way, the global variable's value will keep changing nondeterministically. To get a random number, just read the value of the global variable.

Result:

It works! It's an utterly horrible way to generate random numbers, but hey, it was just an experiment.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UPDATE:

After running the program for around 10 hours, and generating random numbers from 0-9 (inclusive) at around 3-4 numbers per second (over 100,000 numbers), the average of all the numbers was around 4.38. This isn't bad considering the target average for this range of numbers is 4.5.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Source code (Java 1.6) can be found here:
http://www.romanstolper.com/files/RandomThreads.java

No comments:

Post a Comment