Randomness in Computer

The Python module named random allows you to work with pseudorandom numbers. The term "pseudo" indicates that these numbers may look random, as you cannot predict their subsequent values. However, it's important to remember that they are generated using deterministic algorithms, not true randomness.

Random number generators in Python take a value called a seed, which serves as an input to calculate a random number using a specific algorithm. This process produces a new seed value for the next calculation. While the cycle in which all seed values are unique can be very long, it is not infinite. Eventually, the seed values will start repeating, and so will the generated values. This behavior is normal and intended.

Randomness in Computer

The initial seed value, set during program start, determines the order in which the generated values will appear. To add more randomness to the process, you can set the seed using a number taken from the current time. This ensures that each program launch will start from a different seed value, resulting in the use of different random numbers.

Thankfully, Python takes care of this initialization during module import, so you don't need to worry about it in most cases. Keep in mind that true randomness can only come from physical processes beyond our control, like cosmic radiation, while data produced by computers using deterministic algorithms cannot be truly random.

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)
OUTPUT:

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())
OUTPUT:

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))
OUTPUT:

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=',')
OUTPUT:

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)
OUTPUT:

With this explanation and example, it should be easier to understand how the choice() and sample() functions work in Python.

Conclusion

In computer programming, randomness is often required for various tasks. Python provides a module called random that allows you to work with pseudorandom numbers. The term "pseudo" implies that these numbers may appear random, but they are generated using deterministic algorithms, not true randomness.

The random number generators in Python use a seed value as input to calculate random numbers. Each calculation produces a new seed value for the next number. While the sequence of seed values can be very long before repeating, it is not infinite. Eventually, the seed values will start repeating, leading to the repetition of generated numbers. This behavior is normal and expected.

To introduce more randomness into the process, you can set the seed using a value taken from the current time. This ensures that each program launch starts with a different seed value, resulting in the use of different random numbers.

Python takes care of the seed initialization during module import, so in most cases, users don't need to worry about it. However, it's essential to understand that true randomness can only come from physical processes beyond our control, like cosmic radiation. Data produced by computers using deterministic algorithms cannot be truly random.

The random module in Python provides various functions to work with random numbers, such as random() for floating-point numbers in the range (0.0, 1.0), seed() to set the initial seed, and randrange() and randint() for generating integer random values within specified ranges.

When using functions like randrange() and randint() in loops, be cautious about the possibility of repeating values. If you need a set of unique random numbers, you can implement additional logic, like storing generated numbers in a set to keep track of duplicates.

Moreover, Python offers the choice() function to randomly select a single element from a given sequence and the sample() function to randomly choose multiple elements from the input sequence.

Understanding these concepts and functions in the random module allows developers to introduce controlled randomness into their programs and perform various tasks that require random behavior.

End Of Article

End Of Article