- Модуль random на примерах — Изучение методов генерации случайных данных
- Цели данной статьи
- Как использовать модуль random в Python
- Python случайное число float
- # Table of Contents
- # Generate random Float number in Python
- # Rounding the random float to N decimal places
- # Generating N random float numbers rounded to N decimal places
- # Generate random Float within a certain Range using numpy.random.uniform()
- # Generate a List of random Floating-point numbers in Python
- # Generate a list of random floats rounded to N decimals
- # Generate a List of random Floating-point numbers using NumPy
- # Additional Resources
Модуль random на примерах — Изучение методов генерации случайных данных
В данной статье мы рассмотрим процесс генерации случайных данных и чисел в Python. Для этого будет использован модуль random и некоторые другие доступные модули. В Python модуль random реализует генератор псевдослучайных чисел для различных распределений, включая целые и вещественные числа с плавающей запятой.
Список методов модуля random в Python:
Метод | Описание |
---|---|
seed() | Инициализация генератора случайных чисел |
getstate() | Возвращает текущее внутренне состояние (state) генератора случайных чисел |
setstate() | Восстанавливает внутреннее состояние (state) генератора случайных чисел |
getrandbits() | Возвращает число, которое представляет собой случайные биты |
randrange() | Возвращает случайное число в пределах заданного промежутка |
randint() | Возвращает случайное число в пределах заданного промежутка |
choice() | Возвращает случайный элемент заданной последовательности |
choices() | Возвращает список со случайной выборкой из заданной последовательности |
shuffle() | Берет последовательность и возвращает ее в перемешанном состоянии |
sample() | Возвращает заданную выборку последовательности |
random() | Возвращает случайное вещественное число в промежутке от 0 до 1 |
uniform() | Возвращает случайное вещественное число в указанном промежутке |
triangular() | Возвращает случайное вещественное число в промежутке между двумя заданными параметрами. Также можно использовать параметр mode для уточнения середины между указанными параметрами |
betavariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Бета-распределении, которое используется в статистике |
expovariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, или же между 0 и -1 , когда параметр отрицательный. За основу берется Экспоненциальное распределение, которое используется в статистике |
gammavariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Гамма-распределении, которое используется в статистике |
gauss() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Гауссовом распределении, которое используется в теории вероятности |
lognormvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Логнормальном распределении, которое используется в теории вероятности |
normalvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Нормальном распределении, которое используется в теории вероятности |
vonmisesvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении фон Мизеса, которое используется в направленной статистике |
paretovariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении Парето, которое используется в теории вероятности |
weibullvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении Вейбулла, которое используется в статистике |
Цели данной статьи
Далее представлен список основных операций, которые будут описаны в руководстве:
- Генерация случайных чисел для различных распределений, которые включают целые и вещественные числа с плавающей запятой;
- Случайная выборка нескольких элементов последовательности population ;
- Функции модуля random;
- Перемешивание элементов последовательности. Seed в генераторе случайных данных;
- Генерация случайных строки и паролей;
- Криптографическое обеспечение безопасности генератора случайных данных при помощи использования модуля secrets. Обеспечение безопасности токенов, ключей безопасности и URL;
- Способ настройки работы генератора случайных данных;
- Использование numpy.random для генерации случайных массивов;
- Использование модуля UUID для генерации уникальных ID.
В статье также даются ссылки на некоторые другие тексты сайта, связанные с рассматриваемой темой.
Как использовать модуль random в Python
Для достижения перечисленных выше задач модуль random будет использовать разнообразные функции. Способы использования данных функций будут описаны в следующих разделах статьи.
Python случайное число float
Last updated: Feb 22, 2023
Reading time · 5 min
# Table of Contents
# Generate random Float number in Python
To generate a random float in Python:
- Use the random.uniform() method to generate a random float.
- Use the round() function to round the float to N decimal places.
Copied!import random low = 0.5 high = 1.5 # ✅ generate random float with 2 decimal places random_float_2_decimals = round(random.uniform(low, high), 2) print(random_float_2_decimals) # 👉️ 0.51 # ✅ generate random float with 3 decimal places random_float_3_decimals = round(random.uniform(low, high), 3) print(random_float_3_decimals) # 👉️ 0.608
The random.uniform() method generates a random floating-point number.
Copied!import random low = 0.5 high = 1.5 # 👇️ 1.089042238223516 print(random.uniform(low, high)) # 👇️ 0.9282021010721693 print(random.uniform(low, high))
The random.uniform method takes 2 arguments — a and b and returns a floating-point number N such that a
In other words, the method generates a float within the specified range.
Copied!import random low = 0.1 high = 0.7 # 👇️ 0.35799415992456773 print(random.uniform(low, high)) # 👇️ 0.577653189273325 print(random.uniform(low, high)) # 👇️ 0.3361477475326371 print(random.uniform(low, high))
# Rounding the random float to N decimal places
We used the round() function to round the generated random number to N decimal places.
Copied!import random low = 0.5 high = 1.5 random_float_2_decimals = round(random.uniform(low, high), 2) print(random_float_2_decimals) # 👉️ 0.51
We passed 2 as the second argument to the round() function, so the float gets rounded to 2 decimals.
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
The round function returns the number rounded to ndigits precision after the decimal point.
If ndigits is omitted, the function returns the nearest integer.
# Generating N random float numbers rounded to N decimal places
If you need to generate N random floating-point numbers rounded to N decimal places, use a list comprehension.
Copied!import random low = 0.5 high = 1.5 random_floats = [ round(random.uniform(low, high), 2) for _ in range(3) ] print(random_floats) # 👉️ [1.48, 1.17, 1.16]
We used a list comprehension to generate a list of 3 floating-point numbers rounded to 2 decimal places.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we round the number and return the result.
The range class is commonly used for looping a specific number of times in for loops.
Copied!print(list(range(2))) # 👉️ [0, 1] print(list(range(3))) # 👉️ [0, 1, 2]
We used an underscore _ for the name of the variable. There is a convention to use an underscore as the name of placeholder variables we don’t intend to use.
On each iteration, we use the random.uniform() method to generate a random float and return the result.
# Generate random Float within a certain Range using numpy.random.uniform()
You can also use the numpy.random.uniform() method to generate a random float within a range.
The method takes low and high arguments and returns a float within the given range.
Copied!import numpy as np low = 0.1 high = 0.7 float_in_range = np.random.uniform(low=low, high=high) print(float_in_range) # 👉️ 0.21276970453155972 float_in_range = np.random.uniform(low=low, high=high) print(float_in_range) # 👉️ 0.6222178486548654 float_in_range = np.random.uniform(low=low, high=high) print(float_in_range) # 👉️ 0.2633158529588748
Make sure you have the NumPy module installed to be able to run the code sample.
Copied!pip install numpy pip3 install numpy
The numpy.random.uniform method draws samples from a uniform distribution.
Any value within the specified range is equally likely to be returned.
The low keyword argument represents the lower boundary. The generated value is greater than or equal to low .
The high keyword argument is the upper boundary. The generated value is less than or equal to high .
The numpy.random.uniform() method takes an optional size argument in case you need to generate an array of random floats within a given range.
Copied!import numpy as np low = 0.1 high = 0.7 float_in_range = np.random.uniform(low=low, high=high, size=2) print(float_in_range) # 👉️ [0.48012006 0.46810723] float_in_range = np.random.uniform(low=low, high=high, size=3) print(float_in_range) # 👉️ [0.25205676 0.27148159 0.41676953] float_in_range = np.random.uniform(low=low, high=high, size=4) print(float_in_range) # 👉️ [0.47931888 0.30000989 0.68755061 0.16432028]
If you need to convert the NumPy array to a native Python list, use the tolist() method.
Copied!import numpy as np low = 0.1 high = 0.7 float_in_range = np.random.uniform(low=low, high=high, size=2).tolist() print(float_in_range) # 👉️ [0.25542092126863214, 0.12104892506449814]
The tolist method converts a NumPy array to a list object.
# Generate a List of random Floating-point numbers in Python
To generate a list of random floating-point numbers:
- Use a list comprehension to iterate over a range object.
- Use the random.uniform() method to generate random floats within a range.
- Optionally round the floating-point numbers to N decimals.
Copied!import random low = 0.2 high = 0.9 list_of_floats = [random.uniform(low, high) for _ in range(3)] # 👇️ [0.49525149337374097, 0.8635092597733884, 0.5173525204003386] print(list_of_floats)
The first example uses the random.uniform() method to generate random floating-point numbers.
We used a list comprehension to iterate over a range object.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
Copied!import random low = 0.2 high = 0.9 list_of_floats = [random.uniform(low, high) for _ in range(3)] # 👇️ [0.49525149337374097, 0.8635092597733884, 0.5173525204003386] print(list_of_floats)
The range class is commonly used for looping a specific number of times in for loops.
Copied!print(list(range(3))) # 👉️ [0, 1, 2] print(list(range(4))) # 👉️ [0, 1, 2, 3] print(list(range(5))) # 👉️ [0, 1, 2, 3, 4]
We used an underscore _ for the name of the variable. There is a convention to use an underscore as the name of placeholder variables we don’t intend to use.
On each iteration, we use the random.uniform() method to get a random floating-point number within a range.
The random.uniform method takes 2 arguments — a and b and returns a floating-point number N such that a
Copied!import random low = 0.2 high = 0.9 print(random.uniform(low, high)) # 👉️ 0.6596676246120552 print(random.uniform(low, high)) # 👉️ 0.8317441007881621
In other words, the method generates a float within the specified range.
# Generate a list of random floats rounded to N decimals
If you need to round the floating-point numbers to N decimal places, use the round() function.
Copied!import random low = 0.2 high = 0.9 list_of_floats = [ round(random.uniform(low, high), 2) for _ in range(3) ] # 👇️ [0.43, 0.32, 0.63] print(list_of_floats)
On each iteration, we use the random() function to round the float to 2 decimal places.
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
The round function returns the number rounded to ndigits precision after the decimal point.
If ndigits is omitted, the function returns the nearest integer.
# Generate a List of random Floating-point numbers using NumPy
Alternatively, you can use the numpy.random.uniform() method.
The method takes a lower and an upper boundary and generates a list of floating-point numbers within the range.
Copied!import numpy as np low = 0.2 high = 0.9 list_of_floats = np.random.uniform( low=low, high=high, size=(3,) ).tolist() # 👇️ [0.5288858110085052, 0.6832247042689714, 0.6691900820103919] print(list_of_floats)
The numpy.random.uniform method draws samples from a uniform distribution.
Any value within the specified range is equally likely to be returned.
The low keyword argument is a float that represents the lower boundary. The generated values are greater than or equal to low .
The high keyword argument is the upper boundary. The generated values are less than or equal to high .
The size argument is the output shape.
The last step is to use the tolist method to convert the array to a list.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.