V. Generating Random Numbers
Using The Random Function:
rand = random();
The random() function generates a random number between 0 and 1 inclusively.
Example:
rand = random(); // generates a random number between [0-1] and places it in rand.
Generating A Random Integer Between A Range (Inclusively):
rand = rounddown((max_value - min_value + 1)*random(), 1) + min_value;
Example where the max value is 7, and the min value is 2:
rand = rounddown((7-2+1)*random(), 1) + 2;
Explanation:
rounddown((7-2+1)*random(), 1) first generates a random rational number between [0,1] inclusively which is
multiplied by 6 = (7-2+1), producing a rational number between [0-6] inclusively. The application of the
rounddown function then produces an integer between [0-5] with equal probability (see III. Rounding Numbers).
Adding 2 scales the range by 2 resulting in production of an integer between [2-7] with equal probability.
Generating A Random Rational Number Between A Range (Inclusively):
value = (max_value – min_value)*random() + min_value;
Example:
rand = (10 – 5)*random() + 5; //generates a random rational number between [5-10] which is stored rand.