Learn to Code via Tutorials on Repl.it!

← Back to all posts
A Guide to Random Numbers
h
DillonB07

Random Numbers

Have you ever wondered how random numbers work? In this tutorial, I'll be explaining how the Python random module works. This tutorial is for Python, but it will be similar or the same for other languages.

Are random numbers random?

Short answer: No.

Long answer: There is no such thing as true randomness on a computer. An example of true randomness is the rolling of a dice. Random numbers on a computer are not random. They are pseudo-random numbers.

What are pseudo-random numbers?

"Pseudorandomness measures the extent to which a sequence of numbers, though produced by a completely deterministic and repeatable process, appear to be patternless." - Wikipedia

This means that although random numbers look completely random, they're not, and they can be repeated.

Examples

I've created a python file with the following code:

This will print 10 "random" numbers.

Running the program, here is my output:

If I run it again, I get different numbers:

Seems random right? Well what if I told you that we could make it produce the same numbers every time?

Add this line of code before the for loop:

Running the program I get this output:

If I run it again, I get the same output:

This is because, by default, random.seed() uses the seconds past the Epoch. The Epoch is the 1st January 1970.

Let's import time and set the seed to the current time.

Now running the program here is my output:

The first line is the current time. This is in seconds past the Epoch. Then we have our pseudo-random numbers. If we set our random.seed() to the first number, we'll always get the same random numbers generated.

There is a very popular game called Minecraft that uses pseudo-random numbers. In the generation of a world, you can enter a seed. This seed then generates the world. But, if you use the same seed multiple times, the world is always the same. This is the same principle. The worlds are generated based on the seed, just like our numbers are here!

Finished code:

To learn more about Python's random module, check out the documentation: https://docs.python.org/3/library/random.html

Modified version of the program made here:

This will run the generator 100 times and write the results into a file called numbers.txt.

Repl: @DillonB07/pseudo-randomNumbersDemo

Voters
ruiwenge2
UltimatePython
MrVoo
DillonB07
Comments
hotnewtop
UltimatePython

Whoa, I didn't know that, good job!

MrVoo

Wauw, I actually learned something