0% found this document useful (0 votes)
158 views9 pages

Python Random Module Overview

The Python random module provides methods for generating pseudorandom numbers including integers, floats, and sequences. Key methods include seed() to initialize the random number generator, getstate() and setstate() to get and restore the generator's state, randint() and randrange() to generate random integers in a range, and random() to generate floats between 0-1. The module also includes functions for common distributions like normal, exponential, and uniform.

Uploaded by

Bikram Chowdhury
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views9 pages

Python Random Module Overview

The Python random module provides methods for generating pseudorandom numbers including integers, floats, and sequences. Key methods include seed() to initialize the random number generator, getstate() and setstate() to get and restore the generator's state, randint() and randrange() to generate random integers in a range, and random() to generate floats between 0-1. The module also includes functions for common distributions like normal, exponential, and uniform.

Uploaded by

Bikram Chowdhury
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON RANDOM MODULE METHODS

1. seed()
This initializes a random number generator. To generate a
new random sequence, a seed must be set depending on the
current system time. [Link]() sets the seed for random
number generation.

2. getstate()
This returns an object containing the current state of the
generator. To restore the state, pass the object to setstate().

3. setstate(state_obj)
This restores the state of the generator at the point when
getstate() was called, by passing the state object.

4. getrandbits(k)
This returns a Python integer with k random bits. This is
useful for methods like randrange() to handle arbitrary large
ranges for random number generation.

>>> import random


>>> [Link](100) # Get a random integer having
100 bits
802952130840845478288641107953
Here is an example to illustrate getstate() and setstate()
methods.

import random
[Link](1)
# Get the state of the generator
state = [Link]()
print('Generating a random sequence of 3 integers...')
for i in range(3):
print([Link](1, 1000))
# Restore the state to a point before the sequence was
generated
[Link](state)
print('Generating the same identical sequence of 3
integers...')
for i in range(3):
print([Link](1, 1000))
Possible Output:
>>>>Generating a random sequence of 3 integers...
138
583
868
Generating the same identical sequence of 3 integers...
138
583
868
Generate Random Integers
The random module provides some special methods for
generating random integers.
1. randrange(start, stop, step)
Returns a randomly selected integer from range(start, stop,
step). This raises a ValueError if start > stop.
2. randint(a, b)
Returns a random integer between a and b (both inclusive).
This also raises a ValueError if a > b.
Here is an example that illustrates both the above functions.
import random
i = 100
j = 20e7
# Generates a random number between i and j
a = [Link](i, j)
try:
b = [Link](j, i)
except ValueError:
print('ValueError on randrange() since start > stop')
c = [Link](100, 200)
try:
d = [Link](200, 100)
except ValueError:
print('ValueError on randint() since 200 > 100')
print('i =', i, ' and j =', j)
print('randrange() generated number:', a)
print('randint() generated number:', c)
Possible Output
ValueError on randrange() since start > stop
ValueError on randint() since 200 > 100
i = 100 and j = 200000000.0
randrange() generated number: 143577043
randint() generated number: 170
Generating Random floating point numbers
Similar to generating integers, there are functions that
generate random floating point sequences.
[Link]() -> Returns the next random floating point
number between [0.0 to 1.0)
[Link](a, b) -> Returns a random floating point N
such that a <= N <= b if a <= b and b <= N <= a if b < a.
[Link](lambda) -> Returns a number
corresponding to an exponential distribution.
[Link](mu, sigma) -> Returns a number
corresponding to a gaussian distribution.
There are similar functions for other distributions, such as
Normal Distribution, Gamma Distribution, etc.
An example of generating these floating-point numbers is
given below:
import random
print('Random number from 0 to 1 :', [Link]())
print('Uniform Distribution between [1,5] :',
[Link](1, 5))
print('Gaussian Distribution with mean = 0 and standard
deviation = 1 :', [Link](0, 1))
print('Exponential Distribution with lambda = 0.1 :',
[Link](0.1))
print('Normal Distribution with mean = 1 and standard
deviation = 2:', [Link](1, 5))
Possible Output
Random number from 0 to 1 : 0.44663645835100585
Uniform Distribution between [1,5] : 3.65657099941547
Gaussian Distribution with mean = 0 and standard deviation =
1 : -2.271813609629832
Exponential Distribution with lambda = 0.1 :
12.64275539117617
Normal Distribution with mean = 1 and standard deviation =
2 : 4.259037195111757
Random Sequences using the random module
Similar to integers and floating-point sequences, a generic
sequence can be a collection of items, like a List / Tuple. The
random module provides useful functions which can
introduce a state of randomness to sequences.
1. [Link](x)
This is used to shuffle the sequence in place. A sequence can
be any list/tuple containing elements.
Example Code to illustrate shuffling:
import random
sequence = [[Link](0, i) for i in range(10)]
print('Before shuffling', sequence)
[Link](sequence)
print('After shuffling', sequence)
Possible Output:
Before shuffling [0, 0, 2, 0, 4, 5, 5, 0, 1, 9]
After shuffling [5, 0, 9, 1, 5, 0, 4, 2, 0, 0]
2. [Link](seq)
This is a widely used function in practice, wherein you would
want to randomly pick up an item from a List/sequence.
import random
a = ['one', 'eleven', 'twelve', 'five', 'six', 'ten']
print(a)
for i in range(5):
print([Link](a))
Possible Output
['one', 'eleven', 'twelve', 'five', 'six', 'ten']
ten
eleven
six
twelve
twelve
3. [Link](population, k)
Returns a random sample from a sequence of length k.
import random
a = ['one', 'eleven', 'twelve', 'five', 'six', 'ten']
print(a)
for i in range(3):
b = [Link](a, 2)
print('random sample:', b)
Possible Output
['one', 'eleven', 'twelve', 'five', 'six', 'ten']
random sample: ['five', 'twelve']
random sample: ['ten', 'six']
random sample: ['eleven', 'one']
Random Seed
Since pseudorandom generation is based on the previous
number, we usually use the system time to make sure that
the program gives a new output every time we run it. We
thus make use of seeds.
Python provides us with [Link]() with which we can
set a seed to get an initial value. This seed value determines
the output of a random number generator, so if it remains
the same, the output also remains the same.
import random
[Link](1)
print('Generating a random sequence of 4 numbers...')
print([[Link](1, 100) for i in range(5)])
# Reset the seed to 1 again
[Link](1)
# We now get the same sequence
print([[Link](1, 100) for i in range(5)])
Possible Output
Generating a random sequence of 4 numbers...
[18, 73, 98, 9, 33]
[18, 73, 98, 9, 33]
This ensures that we need to be mindful of our seed when
dealing with pseudorandom sequences , since the sequence
may repeat if the seed is unchanged.

Common questions

Powered by AI

The random module handles randomness in generating floating-point numbers through functions like random.random(), which outputs numbers in the range [0.0, 1.0), random.uniform(a, b) for producing numbers within any specified range, and various functions for specific distributions like expovariate() and gauss(). These functions are designed to provide precise control over the range and distribution of floating-point numbers, using underlying algorithms suitable for continuous data, unlike integer functions that focus on discrete random integers .

Gaussian (normal) and exponential distributions are critical in scientific simulations and modeling for their statistical properties. Gaussian distributions, characterized by a symmetric bell curve, are used to model natural phenomena like error distributions due to their central limit theorem properties. Exponential distributions are used in modeling time between events in a Poisson process, common in queuing theory, reliability analysis, and survival studies. These distributions allow simulations to mimic real-world stochastic processes accurately, offering insights and predictive power .

Setting a constant seed value for random number generation in automated testing ensures the reproducibility of test cases. The same sequence of random numbers will be generated each time, which is crucial for debugging and verifying results, as developers can replicate issues and fixes reliably. However, this can also mean a lack of variability in test inputs, potentially overlooking cases that might occur in truly random environments if the test does not include diverse seed values or non-fixed seeds periodically .

random.choice() and random.sample() complement each other by offering different levels of control for element selection from sequences. random.choice() randomly picks a single element, suitable for simple random access needs, while random.sample() allows selecting multiple items with the guarantee of no repetition, ensuring each selected element is unique. Together, they cater to needs ranging from picking singular, possibly repetitive elements, to generating unique subsets representative of the whole sequence, thus broadening the scope of possible random operations on sequences .

Both randrange() and randint() functions in the Python random module are used for generating random integers within specified ranges. However, they behave similarly when invalid ranges are provided, such as when the start or lower bound is greater than the stop or upper bound. In the case of such invalid inputs, both functions raise a ValueError, preventing the generation of a random number and indicating an issue with the range specification .

The random.sample() function is particularly useful for producing non-repetitive selections from a sequence. By specifying the number of items to sample (k), it returns a new list of unique elements randomly picked from the input sequence, ensuring no repetitions. This feature is critical for applications requiring a subset of unique items, such as creating randomized surveys or experimental trials with non-overlapping elements .

The seed() function in the Python random module initializes the random number generator, setting a seed value that determines the starting point for generating a sequence of pseudorandom numbers. It is crucial because pseudorandom number generators are deterministic; using the same seed produces the same sequence of numbers, which is important for reproducibility and debugging. However, without setting the seed, the sequence will vary each time the program runs, typically using the current system time as the default seed .

Shuffling a sequence using random.shuffle() significantly increases randomness in data arrangements, which is valuable in numerous applications such as game development, simulations, or testing. By altering the order of elements in-place, it ensures that each permutation of the sequence is equally likely, thus enabling unbiased randomized conditions or trials. It is particularly useful in scenarios where the order of process execution or data presentation should not introduce an extraneous pattern or bias .

The getstate() function returns an object representing the current internal state of the random number generator. This state can be saved and later restored using the setstate() function, which accepts the state object returned by getstate(). This mechanism allows the generation process to be paused and resumed, or to be returned to a previous point, ensuring continuity or repetition of a specific sequence of random numbers .

The getrandbits(k) function returns an integer with 'k' random bits, which is particularly useful for generating integers over large ranges, beyond the typical fixed-size integer limits. By specifying the number of bits, users can generate arbitrarily large random integers suitable for cryptographic operations, simulations, or any application needing large random numbers .

PYTHON RANDOM MODULE METHODS 
1. seed() 
This initializes a random number generator. To generate a 
new random sequence, a se
802952130840845478288641107953 
Here is an example to illustrate getstate() and setstate() 
methods. 
 
import random 
random
Generating the same identical sequence of 3 integers... 
138 
583 
868 
Generate Random Integers 
The random module provides
print('ValueError on randrange() since start > stop') 
c = random.randint(100, 200) 
try: 
    d = random.randint(200, 10
random.expovariate(lambda) -> Returns a number 
corresponding to an exponential distribution. 
random.gauss(mu, sigma) -> Ret
Exponential Distribution with lambda = 0.1 : 
12.64275539117617 
Normal Distribution with mean = 1 and standard deviation =
2. random.choice(seq) 
This is a widely used function in practice, wherein you would 
want to randomly pick up an item from a
print('random sample:', b) 
Possible Output 
['one', 'eleven', 'twelve', 'five', 'six', 'ten'] 
random sample: ['five', '
Possible Output 
Generating a random sequence of 4 numbers... 
[18, 73, 98, 9, 33] 
[18, 73, 98, 9, 33] 
This ensures that we

You might also like