Generating Random Numbers

  1. Overview
    1. Software must often use random numbers (e.g., creating an AI that chooses randomly between multiple choices, simulating a dice roll, etc.)
    2. Computers typically use random number generators that use mathematical equations to produce pseudorandom numbers, numbers that are not truly random but are nearly impossible to distinguish from truly random numbers
    3. These pseudorandom number generators will produce the same random numbers every time unless they are initialized with a random seed
    4. The seed is often based on the current date and time since time is always changing and never repeated
  2. Example which displays 20 random integers
    #include <iostream>
    #include <cstdlib>   // srand and rand functions
    #include <ctime>     // time function
    using namespace std;
    
    void main()
    {
    	// Seed the random number generator
    	srand(unsigned int(time(NULL)));
    	
    	// Output 20 random numbers
    	for (int i = 1; i <= 20; i++)
    		cout << rand();
    }
    
    1. srand is fed the return value of time which is type-casted into an unsigned integer (an integer that can't be negative)
    2. time(NULL) returns the number of seconds which have elapsed since Jan 1, 1970 (this is called Unix time)
    3. rand returns back a random number between 0 and RAND_MAX (at least 32,767)
    4. Usually the random numbers we want to produce are bound by an upper and lower limit, so we mod the return value from rand
      // Output 20 random numbers between 1 and 10
      for (int i = 1; i <= 20; i++)
      	cout << rand() % 10 + 1;
      
    5. Simulate flipping a coin twenty times
      for (int i = 1; i <= 20; i++)
      {
      	// Number will be 0 or 1
      	if (rand() % 2 == 0)
      		cout << "Heads\n";
      	else
      		cout << "Tails\n";
      }
      
  3. Common mistakes
    1. Forgetting to call srand will result in the same numbers being chosen every time your program runs!
    2. srand only needs to be called once (usually in main). Calling it multiple times is unnecessary and in some cases could cause your program to choose the same random numbers repeatedly
      // Output the SAME 20 random numbers!
      for (int i = 1; i <= 20; i++)
      {
      	srand(unsigned int(time(NULL)));
      	cout << rand() % 10 + 1;
      }
      
  4. Learn more about generating truly random numbers at random.org