Python Random Module: Generating Pseudo-Random Numbers
Have you ever wondered how computer programs generate random numbers? You have probably heard of the term “random”, but did you know that the numbers generated by a computer are not truly random?
Instead, they are called pseudo-random numbers. This means that the numbers seem random, but in fact, they are generated using an algorithm.
In Python, this is implemented using the random module, which provides various functions to generate pseudo-random numbers.
Functions provided by the random module
The random module provides several functions to generate pseudo-random numbers, each with specific use cases.
1. randint()
This function generates a random integer between two given values.
The syntax is: random.randint(a, b)
. Here, ‘a’ is the minimum value and ‘b’ is the maximum value.
2. uniform()
This function generates a random float number between two given values. The syntax is: random.uniform(a, b)
.
‘a’ and ‘b’ are the minimum and maximum values.
3. random()
This function generates a random float between 0 and 1 (inclusive).
The syntax is: random.random()
.
4. choice()
This function returns a random item from a list.
The syntax is: random.choice(list)
.
5. shuffle()
This function shuffles the items of a list in a random order.
The syntax is: random.shuffle(list)
.
Functions that use the global random number generator
The above functions use one global random number generator to generate pseudo-random numbers. But what is this global generator?
Basically, it is a specific function that generates a pseudo-random number when called. The functions listed below provide more control over the generator.
1. seed()
When you call the random number generator, it starts from a fixed point called the seed. If you use the same seed, you will get the same sequence of random numbers every time.
By default, the seed is generated based on the system time. You can also set the seed yourself using the seed()
function.
Example – random.seed(1); random.randint(1, 100)
.
2. getstate() and setstate()
The random number generator has a state, which is a collection of values that determines the sequence of the pseudo-random numbers.
You can get the current state with getstate()
and then reset the generator to that state later with setstate()
. Example – state = random.getstate(); random.setstate(state)
.
3. getrandbits()
This function returns a random integer with a specified size in bits. Example – random.getrandbits(16)
.
4. randrange()
This function returns a random integer between a given start and stop value with a specified step size. The syntax is: random.randrange(start, stop, step)
. Example – random.randrange(1, 10, 2)
.
Why use the Python Random Module?
The Python random module provides you with a way to generate pseudo-random numbers with ease.
It is also useful for creating games, simulations, and other applications that require random behavior. Furthermore, the ability to use the generator’s current state and seed make it possible to generate the same sequence of random numbers every time you run your code.
This can be useful in debugging or other testing scenarios.
Conclusion
The Python random module provides several functions to generate pseudo-random numbers. These functions use one global random number generator to generate pseudo-random numbers.
By using the generator’s seed and state, you can generate the same sequence of random numbers every time you run your code. The random module is an essential tool for creating games, simulations, and other applications that require random behavior.
Generating random integers
Random integers are typically used in a variety of applications, including generating random items from a list, generating random indices for a list, and simulating dice rolling or other board games. Python provides two functions in the random module for generating random integers, which are randrange()
and randint()
.
1. randrange()
The randrange()
function returns a randomly selected integer within the given range. The syntax is as follows: random.randrange(start, stop[, step])
.
Here, start
is the starting value, stop
is the ending value (i.e., it is one value less than the maximum value), and step
is the difference between subsequent values. If step
is not provided, it defaults to 1.
The following example uses the randrange()
function to generate a random integer between 0 and 100, in steps of 2:
import random
x = random.randrange(0, 101, 2)
print(x)
2. randint()
On the other hand, the randint()
function returns a randomly selected integer between two values, including both endpoints. The syntax for randint()
is random.randint(a, b)
where a
is the lower bound and b
is the upper bound.
The following example generates a random integer between 0 and 100:
import random
x = random.randint(0, 100)
print(x)
Generating random floating-point numbers
Python random module’s functions provide a way to generate random floating-point numbers. Often, it is desirable to generate random numbers that are not integers but decimal numbers.
The module offers two functions to generate random floating point numbers. The random()
function returns a random float number between 0 and 1 inclusive.
The function has no parameters, and the syntax for using the function is quite simple. Take a look at the following example that generates a random float between 0 and 1:
import random
x = random.random()
print(x)
Another useful method for generating floating-point numbers is uniform()
that returns a random floating-point number between two given values. The syntax of this function is random.uniform(a, b)
where a
and b
are the given minimum and maximum values of the generated values.
Here is an example:
import random
x = random.uniform(0, 1)
print(x)
Other random distribution functions
Apart from the above-mentioned functions, the random module provides even more functions to generate random numbers of various distributions. Two of the most common generators are expovariate()
and gauss()
.
1. expovariate()
The expovariate()
function generates random numbers following the exponential distribution. The syntax for using the function is random.expovariate(lambd)
where lambd
is an expression that represents the rate parameter of the exponential distribution.
Here is an example:
import random
x = random.expovariate(2)
print(x)
2. gauss()
The gauss()
function returns random numbers following a normal (or Gaussian) distribution. The function takes two arguments, mu
(mean) and sigma
(standard deviation) and returns a random number following the normal distribution.
The syntax for using this function is random.gauss(mu, sigma)
. Here is an example:
import random
x = random.gauss(0, 1)
print(x)
Wrap Up
The Python random module is a powerful tool for generating random numbers in programming. It offers a wide range of functions to generate pseudo-random numbers, including integers, floating-point numbers, and values following various random distributions.
These functions are crucial for simulating events and situations in games and other applications. By understanding how to use the random module functions, it is easy to generate random values in Python.
Generating random sequences
Generating random sequences is an essential part of programming, especially in games, simulations, and optimization problems. Python provides several functions to generate random sequences, including shuffle()
, choice()
, and sample()
.
These functions are useful to randomize a sequence’s order, to select a random item from a list, or to generate a random sample from a sequence.
1. The shuffle() function
The shuffle()
function randomizes the order of elements in a list. The syntax is as follows: random.shuffle(list)
.
Here, list
is the list to be shuffled. The function modifies the list in place, returning None.
The following example demonstrates a basic usage of the shuffle()
function:
import random
a = [1, 2, 3, 4, 5]
random.shuffle(a)
print(a)
The output of the above code could be something like [4, 3, 1, 2, 5]
.
2. The choice() function
The choice()
function is used to get a random item from a list or an iterable sequence. The syntax of choice()
is as follows: random.choice(sequence)
.
Here, sequence
is the desired list or sequence from which a random item should be chosen, and the function returns the randomly selected item. The following example shows how to get a random item from a list:
import random
a = [1, 2, 3, 4, 5]
x = random.choice(a)
print(x)
The output of the above code could be something like 3
.
3. The sample() function
The sample()
function is used to generate a random sample of a given size from a sequence. The syntax of sample()
is as follows: random.sample(sequence, k)
.
Here, sequence
is the desired sequence from which a random sample should be chosen, and k
is the desired sample size. The function returns a new list containing the randomly chosen samples.
The following example shows how to generate a random sample of two items:
import random
a = [1, 2, 3, 4, 5]
x = random.sample(a, 2)
print(x)
The output of the above code could be something like [3, 5]
.
Random Seed
Random numbers generated using the random module are not truly random. Instead, they are generated using an algorithm called pseudorandom number generators.
These generators generate numbers using a mathematical formula that cannot be predicted easily by someone who does not know the formula. However, the sequence of random numbers generated by a pseudorandom number generator is predictable if you know the seed value.
Therefore, the seed value must be changed before every run of your program. The seed value is also important for debugging purposes.
The random.seed()
function sets the seed of the pseudorandom number generator to a given value, which ensures that the sequence of random numbers generated is the same every time the program runs. The syntax is as follows: random.seed(x)
.
Here, x
is the value used to set the seed of the pseudorandom number generator. It could be any integer or a hashable object.
In the following example, we set the seed value to 1 and generate two random integers between 0 and 10. Since the seed value is the same on both runs, the sequence of random numbers generated is the same.
import random
random.seed(1)
print(random.randint(0, 10))
print(random.randint(0, 10))
# Output: 2 9
In this example, we change the seed value to 2 and generate the same two random integers.
import random
random.seed(2)
print(random.randint(0, 10))
print(random.randint(0, 10))
# Output: 8 6
Conclusion
Computer programs require random variations to simulate different scenarios like games, simulations, and other applications. Using Python’s random module, we can generate pseudorandom numbers utilizing different functions.
Additionally, the provided functions shuffle()
, choice()
, and sample()
can be used to randomize any sequence and its items. By setting the random.seed()
value, we can replicate the same pseudo-random sequence every time which can be useful for debugging and testing purposes.
In conclusion, random number generation is a crucial part of programming. The Python random module provides various functions to generate pseudo-random numbers, including integers, floating-point numbers, and values following different distributions.
The shuffle()
, choice()
, and sample()
can be used to randomize any sequence and its items. Setting the random seed value is important for debugging and testing applications.
By understanding and using these functions, you can generate random data to simulate different scenarios in games, simulations, and other applications. The ability to create random numbers provides an essential tool to ensure that programs respond to unpredictable situations smoothly.