Link Search Menu Expand Document

Random

Encryption algorithms, machine learning and making computer games less predictable all require randomness. We can model randomness using random numbers. C# offers ready-made System.Random class for creating random numbers. An instance of the Random class can be used as follows:

namespace sandbox
{
  using System;
  
  class Program
  {
    public static void Main(String[] args)
    {
      Random ladyLuck = new Random(); // create Random object ladyLuck

      for (int i = 0; i < 10; i++)
      {
        // Draw and print a random number
        int randomNumber = ladyLuck.Next(10);
        Console.WriteLine(randomNumber);
      }
    }
  }
}

Above we create an instance of the Random class. It has Next method, which gets an integer as a parameter. The method returns a random number between [0, integer[ or 0..(integer -1).

The program output is not always the same. One possible output is the following:

2 
9 
4 
3 
4 
5 
6 
0 
7 
8

We can use the Next method to create diverse randomness. For example, we might need a program to give us a temperature between [-30,50]. We can do this by first creating random a number between 0 and 80 and then subtracting 30 from it.

Random weatherMan = new Random();
int temperature = weatherMan.Next(81) - 30;
Console.WriteLine(temperature);

A more reasonable way to do this, how ever, is to use Random.Next(lowerLimit, upperLimit), like follows:

Random weatherMan = new Random();
int temperature = weatherMan.Next(-30, 51);
Console.WriteLine(temperature);

NOTICE! The lowerLimit is inclusive but the upperLimit is always exclusive, so we are still getting random between -30 and 50!

A Random object can also be used to create random doubles. These can for example be used for calculating probabilities. Computers often simulate probabilities using doubles between [0..1].

The NextDouble method of the Random class creates random doubles. Let’s assume the weather follows these probabilities:

  • There is 0.1 probability it rains (10%)
  • There is 0.3 probability it snows (30%)
  • There is 0.6 probability the sun shines (60%)

Let’s create a weather forecast using these probabilities.

namespace sandbox
{
  using System;

  public class WeatherMan
  {
    private Random random;

    public WeatherMan()
    {
      this.random = new Random();
    }

    public string Forecast()
    {
      double propability = this.random.NextDouble();

      if (propability <= 0.1)
      {
        return "It rains";
      }
      else if (propability <= 0.4)
      { // 0.1 + 0.3
        return "It snows";
      }
      else
      { // rest, 1.0 - 0.4 = 0.6
        return "The sun shines";
      }
    }
  }
}

Let’s now add a main which uses the WeatherMan class.

namespace sandbox
{
  using System;
  using System.Collections.Generic;

  class Program
  {
    public static void Main(string[] args)
    {
      WeatherMan forecaster = new WeatherMan();

      // save days of the week to a list
      List<string> days = new List<string>();
      days.Add("Mon");
      days.Add("Tue");
      days.Add("Wed");
      days.Add("Thu");
      days.Add("Fri");
      days.Add("Sat");
      days.Add("Sun");

      Console.WriteLine("Next week's weather forecast:");

      foreach (string day in days)
      {
        string weatherForecast = forecaster.Forecast();

        Console.WriteLine(day + ": " + weatherForecast + ".");
      }
    }
  }
}

One output could be

Next week's weather forecast:
Mon: The sun shines.
Tue: It snows.
Wed: The sun shines.
Thu: The sun shines.
Fri: The sun shines.
Sat: It snows.
Sun: It snows.

We can predict how computers work, because they slavishly execute any command we give them. Is a random number generated by a computer then really random?

Random numbers used by computer programs are typically pseudorandom. They seem like random numbers, but in reality they follow some algorihmically created series of numbers. Most of the time pseudorandom is good enough – for example the user will not notice any difference when YouTube random play is pseudorandom. On the other hand if random numbers are used for scientific calculations, using a weak pseudorandom number generator can lead to questionable results. One example is IBM’s RANDU which was used for a short while in the 1960’s.

All randomness in computer programs is not pseudorandom. Programs aiming for stronger randomness use, among other things, real life random phenomena to generate random numbers. For example space radiation or lava lamps are thought to be random phenomena.

You can read more about randomness from https://www.random.org/randomness/.