Selected Functions From The Random Module
In this section, we will cover some of the random function offered by random module in python. This includes random(), seed(), randrange(), and randint().
The random()
Function
The random()
function is a general-purpose function that generates a floating-point number x in the range of $(0.0, 1.0)$. In other words, the generated value x satisfies the condition: $0.0 <= x < 1.0$.
import random
# Produces five pseudorandom values using the random() function
for _ in range(5):
value = random.random()
print(value)
The provided example program demonstrates the usage of the random()
function to generate five pseudorandom values. Since these values depend on the current seed value (which is usually unpredictable), they cannot be easily guessed or predicted.
The seed()
Function
The seed()
function is used to set the initial seed for the random number generator, ensuring that it produces the same sequence of random values every time the program is run with the same seed. There are two variants of the seed()
function:
seed()
- When called without any arguments, it sets the seed based on the current system time. This is often used when you want a different sequence of random numbers on each run.
seed(int_value)
- When called with an integer value int_value, it sets the seed to the provided integer. This is useful when you want to reproduce the same sequence of random numbers across different runs of the program.
Here's an example of how the seed()
function works:
from random import random, seed
seed(0)
for i in range(5):
print(random())
Note: The exact values may vary slightly on different systems due to variations in floating-point arithmetic precision, but the general sequence remains the same.
The randrange
and randint
Function
If you want integer random values, you can use the following functions:
randrange(end)
: Generates a random integer from the range [0, end) (excluding end).
randrange(start, end)
: Generates a random integer from the range [start, end) (excluding end).
randrange(start, end, step)
: Generates a random integer from the range starting at 'start', up to 'end', with a step size of 'step' (excluding end).
Another option is to use the randint(left, right)
function, which generates an integer value within the range [left, right] (inclusive on both ends). It's equivalent to randrange(left, right+1)
.
Please note that the functions randrange and randint can produce repeating values if the number of subsequent invocations is not greater than the width of the specified range.
Here's a sample program that outputs four random integer values:
from random import randrange, randint
print(randrange(1), end=' ')
print(randrange(0, 1), end=' ')
print(randrange(0, 1, 1), end=' ')
print(randint(0, 1))
This program will output a line consisting of three zeros and either a zero or one at the fourth place.
Avoiding Repeating Values
If you need a set of unique random numbers, be cautious when using the functions in a loop. For example, in the code below, there's a high chance of getting repeating numbers:
from random import randint
for i in range(10):
print(randint(1, 10), end=',')
To ensure uniqueness, you can use additional logic like storing the generated numbers in a set to keep track of what has been generated so far and discard duplicates.
The choice
and sample
Function
Choice Function:
The choice(sequence) function allows you to randomly select a single element from the given input sequence and returns that element. In other words, it picks one random item from the list and gives you that item as the result.
Sample Function:
The sample(sequence, elements_to_choose) function provides a way to randomly choose multiple elements from the input sequence and returns them as a list. The number of elements to choose is specified by the elements_to_choose argument.
Important Note:
For the sample() function, the number of elements to choose (elements_to_choose) should not exceed the length of the input sequence. Otherwise, it will raise an error.
Here's an example of how you can use these functions in Python:
from random import choice, sample
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Example 1: Using choice() function to pick a single element
random_element = choice(my_list)
print("Randomly chosen element:", random_element)
# Example 2: Using sample() function to pick multiple elements
sampled_elements = sample(my_list, 5) # Choose 5 random elements from my_list
print("Sampled elements:", sampled_elements)
# Example 3: Trying to choose more elements than the list contains will raise an error
try:
too_many_elements = sample(my_list, 10) # Trying to choose 10 elements from my_list
print("Too many elements chosen:", too_many_elements)
except ValueError as e:
print("Error:", e)
With this explanation and example, it should be easier to understand how the choice()
and sample()
functions work in Python.