Random numbers

From Applied Science

For this introductory level, random numbers are not studied. They show up when we need to test programs with random inputs. To study algorithms that generate random numbers or the mathematical theory behind them is not a subject to be discussed at this stage.

Random numbers do not obey to any law or formula, therefore they are impossible to be generated by any computer running some algorithm. The numbers that we see are pseudo-random, numbers that have a law of formation given by an algorithm, but are random enough for our purposes at this stage nevertheless. A pseudo-random number generator relies on a seed, some input number to generate a sequence of numbers where one number does not have any relationship with the previous one, except for the algorithm itself. The same seed always result in the same sequence, therefore we need a random seed to get different numbers each time the algorithm is run.


What comes below requires knowledge about functions and functions of VOID type


  • A program that simulates tossing a coin:

#include <stdio.h>
#include <stdlib.h>

int main() {

int head = 0, tails = 0, d, coin;
srand(9);

for (d = 0; d < 5000; d++) {

coin = rand() % 2;
if (coin == 0) tails++;
else head++;

}

printf("tails: %d\nhead: %d", tails, head);

}

Library stdlib.h It's where the functions rand() and srand() are found. The random distribution of the numbers is verified by the nearly even distribution of head and tails. We could write a function with a formula to generate pseudo-random numbers, but it would need to be a pretty good formula to get good results.

The srand() function. It needs an argument to be called, any number works. For some chosen number, the output should always be the same sequence of pseudo-random numbers. The function call must be made outside the loop, else the same seed is inputted again and, therefore, the same number is generated. As a result, the loop iterates thousands of times for the same number. Remember that functions cannot output different results for the same input, that violates the mathematical definition of functions.

To save the user from inputting a seed, you can use the #time.h library. Replace the seed with "time(0)". That makes the seed be a number of seconds counted from a certain date.

The rand() function. It does not have any parameters, it "chooses" a number generated by the srand() function and generates another in between the 0 to RAND_MAX range. The function srand() is of VOID type, whereas rand() is of INT type. That's why we cannot use srand() as an argument for printf(), because srand() doesn't return anything. At each loop's iteration a different value is returned by srand(), which ensures the even distribution of the results between HEAD and TAILS.