Random numbers are very important in computing. Whenever you need to simulate something in the real world where the outcome is unknown, random numbers come into play. A classic example is their use in games where you may want to simulate the throw of a die, for example.
Some of the applications of random numbers in computing are listed below.
- Statistical sampling
- Machine Learning
- Recaptcha for human verification on websites
It is interesting to note that random numbers are often not truly random, in the sense that if you know the starting point and you know the algorithm being used you can predict the next number in the sequence. However for many practical purposes this “pseudo-randomness” is perfectly adequate.
Python Random Integers
In Python, we work with random numbers using the
random module, which we import using
import random. There are many tools available in the module, but for now we will just focus on
. syntax here means “the randint() method of the random module.”
random.randint(arg1, arg2) generates a random integer (whole number) between the first and second arguments, inclusive.
Run the code below in your favourite Python editor.
import random # Print a random integer between 1 and 10 inclusive. print(random.randint(1, 10)) # Let's do it a few times to check it's working as expected. for i in range(10): print(random.randint(1, 10), end=",") # end="," keeps the output on the same line, with commas between.
- See if you can understand why you get the output that you do
- Try some different ranges for the arguments to
Random sampling with Python
We can use list comprehension to generate a list of random integers like so:
import random # Create a list of random integers between 1 and 100, inclusive. data = [random.randint(1, 100) for _ in range(20)] print(data)
Note the use of
_ for the range variable. Since we don’t explicitly use it, we don’t need to name it.
[61, 41, 39, 42, 83, 50, 76, 89, 59, 63, 72, 10, 63, 59, 51, 22, 64, 34, 10, 12]
Now that we have some data, we can sample from it like so:
The arguments here are the data to sample from, and the size of the sample. Note that with this method, you will not get duplicate samples.
[96, 43, 59]
There is a lot more you can do with random numbers is Python, but the two methods of the
random module covered here,
random.sample() are a great start, and I recommend that you play and experiment with them until you are confident with how they work. Then perhaps you can use them in your own programs.