Python. Module random. Random number generation. Classes Random, SystemRandom. Bookkeeping functions. Functions for integers




Module random. Random number generation. Classes Random, SystemRandom. Bookkeeping functions. Functions for integers


Contents


Search other websites:

1. Purpose and connection of the random module. Categories of processed numbers

The random module implements tools that allow you to generate pseudo-random numbers. The functions of the random module process the following categories of numbers:

  • integers;
  • sequences of numbers;
  • real numbers (floating point numbers).

Also, the random module implements various additional means of generating random numbers.

To use functions from the random module, you first need to include this module using the command

import random

 

2. The purpose of Random and SystemRandom classes

To work with random numbers in the random module, two main hidden classes can be distinguished:

  • class Random;
  • class SystemRandom.

The instance of the Random class provides all the necessary functions. To obtain generators independent of the current state of an instance of the Random class, you can create your own instances of this class. To get your own number generator, you need to override the methods of the Random class: random(), seed(), getstate() and setstate().

The SystemRandom class contains the os.urandom() system function, which generates random numbers from sources provided by the operating system.

 

3. Function random(). Example

All Python functions are based on the use of the random() function, which generates a floating-point number in the semi-open range [0.0, 1.0].

The random() function uses the so-called Mersenne Twister, which is based on the properties of Mersenne primes. The study of this method of generating random numbers can be found in other sources. The generator gives a value with an accuracy of 53 digits and has a period of 2 ** 19937-1.

Example. In the example, a random number is written to the variable x using the random() function

# include the random module
import random

# generate a random number
x = random.random() # x = 0.016419749852326193


 

4. Bookkeeping functions
4.1. Function random.seed(). Example

The random.seed() function initializes a random number generator. The function has the following general form

random.seed(a = None, version = 2)

here

  • a – integer value from which to start generating random numbers. If parameter a is omitted, then the current system time is used. System time can be obtained from the operating system using the os.urandom() function;
  • version – a parameter that can take one of two values: version = 2 (default) and version = 1. If version = 2 (by default), then the str, bytes or bytearray object is converted to int, and all its bits are used. In version = 1 mode, it is assumed that sequences are used for older versions of Python, and therefore the algorithm for types str and bytes generates a narrower range of seed numbers.

Example.

# Function random.seed() - initializes random number generator
# include random module
import random

# Case 1. The function uses the number 5 to generate a sequence.
random.seed(5)
x = random.random() # x = 0.6229016948897019
y = random.random() # y = 0.7417869892607294

random.seed(5) # the same numbers as in x, y - the values are repeated
z = random.random() # z = 0.6229016948897019
v = random.random() # v = 0.7417869892607294

# Case 2. The function uses the system time to generate a sequence.
# System time is constantly changing
random.seed()
x = random.random() # x = 0.7662531463810477
y = random.random() # y = 0.9435964177952566

random.seed() # the values of x, y, z, v are different
z = random.random() # z = 0.927815953637931
v = random.random() # v = 0.9508059701409717

The above code clearly demonstrates the role of the random.seed() function in generating a sequence of random numbers using the random() function as an example. Two cases of using the random.seed() function are considered:

  • with integer parameter 5;
  • without parameter.

In the first case, the function receives parameter 5 twice

random.seed(5)

As a result, the sequence of random numbers is repeated. The values of the variables x, y are the same as the values of the variables z, v.

In the second case, the function does not use the parameter

random.seed()

In this case, the first random number is obtained from the system time, which is constantly changing. As a result, the values of the variables x, y, z, v will be different.

 

4.2. Functions random.getstate() and random.setstate(). Example

Using the random.getstate() function, you can save the internal state of the random number generator as an object

objName = random.getstate()

where objName – the name of object.

Using the random.setstate() function, you can restore the internal state of the random number generator that was previously saved by the random.getstate() function. The general form of calling the random.setstate() function is as follows

random.setstate(objName)

where objName – name of the object in which the state of the generator is previously stored.

Example.

# Functions random.getstate(), random.setstate()
# include random module
import random

random.seed() # initialize the generator with some initial value
obj = random.getstate() # save the state in obj object
x = random.random() # get a random number

# initialize the generator with a different initial value
random.seed() # we obtain a new sequence of random numbers

random.setstate(obj) # restore state from object 'obj'
y = random.random() # get previously saved number

# output the result
print('x =', x)
print('y =', y)

The result of the program

x = 0.2056527930645382
y = 0.2056527930645382

As can be seen from the result, the x and y values are repeated. This means that by calling a function

random.setstate(obj)

it is possible to restore a sequence of random numbers (state), which was previously stored in the obj object by calling

obj = random.getstate()

The example intentionally creates a new sequence of random numbers by calling

random.seed()

in order to modify a previously created sequence.

 

4.3. Function random.getrandbits(). Example

The random.getrandbits() function returns an integer from the range, which is formed by the number of bits.

random.getrandbits(k)

where k – the number of bits of an integer that take part in the formation of a random value.

If k = 3, then numbers from the range 0..7 or (2**3-1) are obtained. If k = 8, then numbers from the range 0..2**8-1 or 0..255 are obtained.

Example.

# Function random.getrandbits()
# include the random module
import random

# Case 1. Number of bits = 4
print('Number of bits = 4')
i = 0
while i<10:
    x = random.getrandbits(4) # numbers in the range 0..2**4 => 0..15
    print(x, ' ')
    i=i+1

# Case 2. Number of bits = 5
print('Number of bits = 5')
i = 0
while i<10:
    x = random.getrandbits(5) # numbers in the range 0..2**5 => 0..32
    print(x, ' ')
    i=i+1

The result of the program

Number of bits = 4
5
5
15
6
11
2
10
14
12
0
Number of bits = 5
4
9
4
18
28
19
5
29
17
31

 

5. Functions for integers
5.1. Function random.randrange(). Setting a range of random values

The random.randrange() function sets the range of values within which a random number is generated by the random.randint() function. The function has several implementations:

random.randrange(stop)
random.randrange(start, stop [, step])

where

  • stop – a numeric integer value defining the largest number that can be generated (upper bound of the range);
  • start – a numeric integer value defining the smallest number that can be generated (lower bound of the range);
  • step – a value that sets the difference (step) between two adjacent possible values of random numbers. That is, random numbers are multiples of the value of step. For example, if step = 4, then random numbers will be a multiple of 4: 8, 16, 40, 28 …

Example. The example demonstrates the operation of the random.randrange() function for a different number of parameters.

# Function random.randrange()
# include random module
import random

# Case 1. With two parameters
# generating 5 random integers in the range [0, 19]
print('Function random.randrange(0,20)')
i=0
while i<5:
    d = random.randrange(0,20)
    print(d)
    i = i+1
print

# Case 2. With one parameter
# generating 5 random integers in the range [0, 9]
print('Function random.randrange(10)')
i=0
while i<5:
    d = random.randrange(10) # random.randrange(9+1)
    print(d)
    i = i+1
print

# Case 3. With three parameters
# generated numbers multiples of 3
print('Function random.randrange(0,20,3)')
i=0
while i<5:
    d = random.randrange(0,20,3)
    print(d)
    i = i+1

The result of the program

Function random.randrange(0,20)
6
7
18
9
7

Function random.randrange(10)
1
0
1
0
7

Function random.randrange(0,20,3)
6
3
0
12
15

 

5.2. Function random.randint(). Getting an integer random number

The random.randint() function returns a random integer N that is within the boundaries of [a, b], that is,

a <= N <= b

Example.

# Function random.randint()
# include random module
import random

# print 10 numbers in the range [200..300]
i=0
while i<10:
    d = random.randint(200,300)
    print(d)
    i = i+1

The result of the program

231
281
286
211
250
200
256
232
203
242

 


Related topics