Python random number generator code

Introduction

Ready for more code snippets? In this post, we are going to talk about random numbers in Python. Have you ever thought about what random means or even if randomness makes any sense in the context of computing! (as computers execute instructions blindly). Is randomness useful? can we apply it in real life computational problems?. Let us try to answer these questions (as always) using an easy to follow language…

What is a random number?

Imagine we are rolling a die. What are the outcomes of this experiment? Obviously, a discreet number between 1 and 6. It is a finite number of possible outcomes but we cannot be exactly sure which number we are going to get next. This is an example on discreet random numbers between 1 and 6. We can also generate continuous random numbers. For example, generating a fraction between 0 and 1. There are infinite fractions between 0 and 1. The math behind randomness is beyond the scope of this article, however it should not hurt to say a word here. This topic is taught in statistics and probability courses. If you are curious, you may check probability density functions (or distribution functions). A uniform distribution is the one in which all outcomes have the same likelihood of occurance (ex. rolling a die). You probably heard of the normal distribution or the Gaussian distribution (bell curve shape) in which the likelihood of an event is close to the average. For example, if we have a class of students then most of the scores are distributed around the average. Very few students are top of the class and very few are poor performers. To chose a random sample from a given distribution is also a separate topic in mathematics which is not covered here. Putting mathematics aside, let us see how random numbers are generated using a programming language like Python…

Types of random number generators

As we indicated earlier, computers are not random in nature as machines follow instructions to the letter. In theory, we cannot generate true random numbers using computers unless the algorithm is hooked into some external random source. With that said, we can classify random number generators into two types…

  • True random generators: random numbers are generated by observing a natural random event (ex. lightning in winter). It comes with a price. It is not easy to implement and inconvenient
  • Pseudo (i.e. fake) random generators: random numbers are generated using a formula. The generated sequence of numbers look random but in reality they are not. In other words, if the formula and the starting point (i.e. called seed) is known in advance, then we can predict the next outcome. This method is efficient, easy to implement and very convenient

Pseudo random number generators are useful and can be applied in various applications (ex. simulation, modeling, games, etc). For more serious applications (ex. encryption keys, lottery, etc) pseudo random generators should not be used, otherwise the system can be compromised. A good pseudo random number generator should have the following characteristics…

  • Uniform distribution: the generated numbers should not repeat often
  • Hard to guess: generated numbers are not easy to predict
  • Efficient: does not take long time to generate
  • Deterministic: this is handy if we want to replay the generated numbers

Pseudo random number generators suffer from the fact that they are periodic. The generated sequence will eventually repeat itself. Although this is an undesired characteristic, new algorithms are developed to extend the period so that it is ignored for practical purposes.

How are random numbers generated?

Pseudo random number generators use a recurrence formula. To start the sequence, we provide the recurrence with an initial value called the seed. Starting with the same seed will generate the same sequence that is why the seed need to be random for example depending on current system time. One of the most common algorithms for generating random numbers is the linear congruential generator…

Linear congruential generator in Python

This generator is defined by the following recurrence relation…

Where:

  • 0 < m is the modulus
  • a is the multiplier 0 < a < m
  • c is the increment 0<= c < m
  • x0 is the seed 0 <= x0 < m

Here is the implementation in Python…

Python random module

Python offers a dedicated module for generating pseudo random numbers called random. In the subsequent sections, we are going to skim through some of the built in functions exposed by the random module…

Python random function

random built in function generates a fractional random number between 0 and 1. Here is an example…

If you run the code snippet above, you should get something like…

Python randint function

randint built in function generates a random integer number within a given range. Here is an example…

If you run the code snippet above, you should get something like…

Python randrange function

randrange built in function is similar to randint as it also generates random integers within a range but there are two differences…

  • Range end number is excluded
  • Provides a step parameter to skip numbers

Here is an example…

If you run the code snippet above, you should get something like…

Python uniform function

uniform built in function generates a random float number with a given range. Here is an example…

If you run the code snippet above, you should get something like…

Python choice function

choice built in function randomly picks an item from a list. Here is an example…

If you run the code snippet above, you should get something like…

Python shuffle function

shuffle built in function changes the order of list items in random way in place. Here is an example…

If you run the code snippet above, you should get something like…

Python sample function

sample built in function shuffles an immutable sequence and return a new shuffled list. Note that the original list is unchanged. Here is an example…

If you run the code snippet above, you should get something like…

Difference between choice and sample

The difference is pretty straightforward. sample function returns a new list and does not change the original list in place as in shuffle function. Also, the sample function provides a parameter to specify the number of elements to pick.

Random numbers for security

As we mentioned earlier, pseudo random number generators are not a good fit for secure applications. If you want to use a random number generator that is not reproducible, then you can use system random generator. Here is an example…

If you run the code snippet above, you should get something like…

That is all for today, let us summarize…

Summary

  • Computers are not random. They follow instructions blindly. To generate a true random number, the computer has to be hooked into an external random source
  • Pseudo or fake random numbers can be generated using recurrence formula and starting number called the seed
  • Python offers a dedicated module for generating pseudo random numbers called random
  • random built in function generates a fractional random number between 0 and 1
  • randint built in function generates a random integer number within a given range
  • randrange built in function is similar to randint as it also generates random integers within a range but it allows us to skip numbers
  • uniform built in function generates a random float number with a given range
  • choice built in function randomly picks an item from a list
  • shuffle built in function changes the order of list items in random way in place
  • sample built in function shuffles an immutable sequence and return a new shuffled list. The original list is unchanged
  • Pseudo random number generators are not a good fit for security applications. Use system random generator instead

References

Thanks for visiting. Please use the comments section below for questions.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *