We are going to be using mathematical methods to produce sequences of numbers that appear to be random. In actual fact the sequence of numbers can be predicted but to a user they will appear random. They are known as pseudo-random numbers. The method we will use is called the linear-conguential method. For this method we start with some integer, called a seed, and then keep applying this formula
seed := (MULTIPLIER * seed + INCREMENT) mod MODULUSMULTIPLIER, INCREMENT and MODULUS are constants. If you choose appropriate values for these constants then the successive values of seed will be randomly distributed over the range 0 <= seed < MODULUS. Suppose that we had the constants defined as MULTIPLIER = 5, INCREMENT = 3 and MODULUS = 8 and that seed had a starting value of 2. If we use the formula here are the next values of seed that we will obtain.
seed = (5 * 2 + 3) mod 8 = 13 mod 8 = 5
seed = (5 * 5 + 3) mod 8 = 28 mod 8 = 4
seed = (5 * 4 + 3) mod 8 = 23 mod 8 = 7
seed = (5 * 7 + 3) mod 8 = 38 mod 8 = 6
Let's look at a making our own random function using this approach. Here is the code.
|
So let's start using our function. Suppose we had the following declarations:
|
To simulate rolling a single 6-sided die we would need a random number in the range {1, 2, 3, 4, 5, 6}. Here is a statement that uses our function and sets the variable die to a number from that set:
die := floor(random(seed) * 6) + 1To make the variable card equal to a random number in the set {1, 2, 3, .. 52} we would say:
card := floor(random(seed) * 52) + 1Here is a program that picks 10 random numbers between 100 and 200 (inclusive) and prints them:
|
197 177 127 155 138 128 190 193 156 173 |
114 178 199 172 151 137 138 107 104 133 |
var seed : int := Time.Sec mod 1000The statement Time.Sec calls a function that returns the number of seconds since January 1, 1970. We mod it with 1000 so the number won't be too big for our random function. This way our starting seed is unpredictable. When you are testing a program with random values it is convenient to be able to specify a specific value for seed. That way you get the same results every time and it is easier to fix bugs. When your program is complete then you can use Time.Sec to get really random results.
|