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…
1 |
Xn+1 = (a * Xn + c) % m |
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…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Linear congruential generator class class LinCongGen: # Constructor initialize with seed def __init__(self, seed=1): # Next value self.xn = seed # Multiplier self.a = 1 # Increment self.c = 2 # Modulus self.m = 3 # Generate a random number def generate(self): self.xn = (self.a * self.xn + self.c) % self.m return self.xn # Test the generator with different seeds lcg = LinCongGen() for i in range(5): lcg.seed = i print("seed = {}".format(i)) # Generate 5 random numbers for j in range(5): print(lcg.generate()) |
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…
1 2 3 4 5 6 7 8 9 |
# Import random module import random # Print 5 random floats between 0 and 1 for i in range(5): print(random.random()) # Print 5 random floats between 0 and 100 for i in range(5): print(100 * random.random()) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 6 7 8 9 10 |
0.176390674549 0.931725029187 0.0299940540494 0.161881184608 0.886180863975 10.9864215198 14.5421920722 75.980696932 84.9372763218 74.323051427 |
Python randint function
randint built in function generates a random integer number within a given range. Here is an example…
1 2 3 4 5 6 |
# Import random module import random # Print 10 random integers between 5 and 10 # Note that both 5 and 10 are included in the range for i in range(10): print(random.randint(5, 10)) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 6 7 8 9 10 |
6 5 10 9 6 10 5 6 6 6 |
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…
1 2 3 4 5 6 7 |
# Import random module import random # Print 10 random integers between 0 and 10 # Note that 10 is not included in the range # Note also that a step of 3 is used for i in range(10): print(random.randrange(0, 10, 3)) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 6 7 8 9 10 |
6 3 9 3 9 6 9 3 9 3 |
Python uniform function
uniform built in function generates a random float number with a given range. Here is an example…
1 2 3 4 5 |
# Import random module import random # Print 10 random floats between 1 and 10 for i in range(10): print(random.uniform(1, 10)) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 6 7 8 9 10 |
7.86782616561 7.89317141987 4.24995801885 3.88212481192 4.42068069444 7.59474056871 5.55880935681 9.08185370674 1.49278271759 3.87171112333 |
Python choice function
choice built in function randomly picks an item from a list. Here is an example…
1 2 3 4 5 6 7 8 9 |
# Import random module import random # Define a list lst = ['red', 'green', 'blue', 'black', 'white', 'orange', 'brown', 'yellow'] # Pick 5 random colors (5 times not in one shot) for i in range(5): print(random.choice(lst)) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 |
brown yellow brown yellow blue |
Python shuffle function
shuffle built in function changes the order of list items in random way in place. Here is an example…
1 2 3 4 5 6 7 8 9 10 |
# Import random module import random # Define a list lst = ['red', 'green', 'blue', 'black', 'white', 'orange', 'brown', 'yellow'] # Shuffle the list 5 times for i in range(5): random.shuffle(lst) print(lst) |
If you run the code snippet above, you should get something like…
1 2 3 4 5 |
['black', 'white', 'orange', 'brown', 'blue', 'green', 'red', 'yellow'] ['green', 'white', 'orange', 'black', 'brown', 'blue', 'red', 'yellow'] ['yellow', 'white', 'green', 'blue', 'red', 'orange', 'brown', 'black'] ['yellow', 'orange', 'white', 'red', 'blue', 'brown', 'green', 'black'] ['brown', 'orange', 'blue', 'green', 'black', 'red', 'white', 'yellow'] |
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…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Import random module from random import sample # Define a list colors = ['red', 'green', 'blue', 'black', 'white', 'orange', 'brown', 'yellow'] # Pick one color c = sample(colors, 1) print(c) # Pick two colors c = sample(colors, 2) print(c) |
If you run the code snippet above, you should get something like…
1 2 |
['blue'] ['yellow', 'orange'] |
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…
1 2 3 4 5 6 7 8 9 10 11 |
# Import random module import random # Create a system random generator rg = random.SystemRandom() # Print some random numbers # This should print a float between 0 and 1 print rg.random() # This should print an integer between 0 and 100 print rg.randint(0, 100) |
If you run the code snippet above, you should get something like…
1 2 |
0.597373937766 29 |
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.