Arranging the usage of random function in Python

Table of contents

1. random.random(): returns a floating-point number randomly generated in the range [0,1)

2. random.uniform(a, b): returns a randomly generated floating-point number in the range [a, b)

3. random.randint(a,b): generate an integer within the specified range 

4. random.randrange([start],stop[,step]): It is used to obtain a random number from the collection within the specified range and incremented by the specified base. 

5. random.choice(): Get a random element from the specified sequence

6. random.shuffle(x[,random]): Used to shuffle the elements in a list and sort them randomly

7. random.sample(sequence,k): It is used to randomly obtain a fragment of a specified length from a specified sequence, and the sample() function will not modify the original sequence.

8. np.random.rand(d0, d1, …, dn): returns one or a set of floating point numbers, the range is between [0, 1)

9. np.random.normal(loc=a, scale=b, size=()): returns the probability density random number of the normal distribution (Gaussian distribution) satisfying the condition of mean=a, standard deviation=b

10 np.random.randn(d0, d1, … dn): returns random numbers with probability density of standard normal distribution (mean=0, standard deviation=1)

11. np.random.standard_normal(size=()): returns the probability density random number of the standard normal distribution (mean=0, standard deviation=1)

12. np.random.randint(a, b, size=(), dtype=int): returns a random integer in the range [a, b) (containing repeated values)

13. random.seed(): set random seed


First we need to import the random module 

1. random.random() : returns a floating point number randomly generated, the range is between [0,1)

import random
print(random.random())

2. random.uniform(a, b) : returns a floating point number randomly generated, the range is between [a, b)

import random
print(random.uniform(1,5))

3.  random.randint(a,b) : generate an integer within the specified range 

import random
print(random.randint(1,10))

4.  random.randrange([start],stop[,step]) : It is used to obtain a random number from the collection within the specified range and incremented by the specified base. 

For example random.randrange(10,100,2) , the result is equivalent to getting a random number from the sequence [10,12,14,16...96,98]. random.randrange (10,100,2) is equivalent in result to random.choice(range(10,100,2)).

import random
print(random.randrange(10,22,3))

5.  random.choice() : Get a random element from the specified sequence

random.choice() obtains a random element from the sequence, its prototype is random.choice(sequence) , and the parameter sequence represents an ordered type. Let me explain here that sequence is not a specific type in Python, but generally refers to a sequence data structure . Lists, tuples, and strings all belong to sequence .

import random
print(random.choice('学习python'))   # 从字符串中随机取一个字符
print(random.choice(['good', 'hello', 'is', 'hi', 'boy']))   # 从list列表中随机取
print(random.choice(('str', 'tuple', 'list')))   # 从tuple元组中随机取

6.  random.shuffle(x[,random]) : Used to shuffle the elements in a list and sort them randomly

import random
p=['hehe','xixi','heihei','haha','zhizhi','lala','momo..da']
random.shuffle(p)
print(p)
x = [1, 2, 3, 4, 5]
random.shuffle(x)
print(x)

7.  random.sample(sequence,k) : It is used to randomly obtain fragments of the specified length from the specified sequence, and the sample() function will not modify the original sequence.

import random
list1=[1,2,3,4,5,6,7,8,9,10]
slice=random.sample(list1,5)
print(slice)
#[8, 3, 5, 9, 10]
print(list1)
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = random.sample(range(0, 10), 5)
print(x, type(x))
#[9, 2, 7, 8, 6] <class 'list'>
Words = "AppleKMedoide"
print(random.sample(Words, 3))
#['p', 'M', 'A']
print(random.sample(Words, 3))
#['d', 'i', 'l']

The following functions need to call the numpy library 

8. np.random.rand(d0, d1, …, dn) : returns one or a set of floating point numbers, the range is between [0, 1)

import random
import numpy as np
x = np.random.rand()
y = np.random.rand(4)
print(x,type(x))
#0.09842641570445387 <class 'float'>
print(y,type(y))
#[0.27298291 0.12350038 0.63977128 0.90791234] <class 'numpy.ndarray'>

9. np.random.normal(loc=a, scale=b, size=()) : returns the probability density random number of the normal distribution (Gaussian distribution) satisfying the condition of mean=a, standard deviation=b

np.random.normal(loc=a, scale=b, size=()) - Returns the probability density random number of the normal distribution (Gaussian distribution) satisfying the condition of mean=a, standard deviation=b, size defaults to None (returns 1 random number), can also be int or array

import random
import numpy as np
x = np.random.normal(10,0.2,2)
print(x,type(x))
#[9.78391585 9.83981096] <class 'numpy.ndarray'>
y = np.random.normal(10,0.2)
print(y,type(y))
#9.871187751372984 <class 'float'>
z = np.random.normal(0,0.1,(2,3))
print(z,type(z))
#[[-0.07114831 -0.10258022 -0.12686863]
# [-0.08988384 -0.00647591  0.06990716]] <class 'numpy.ndarray'>
z = np.random.normal(0,0.1,[2,2])
print(z,type(z))
#[[ 0.07178268 -0.00226728]
# [ 0.06585013 -0.04385656]] <class 'numpy.ndarray'>

10 np.random.randn(d0, d1, … dn): returns random numbers with probability density of standard normal distribution (mean=0, standard deviation=1)

np.random.randn(d0, d1, ... dn): Returns a probability density random number from a standard normal distribution (mean=0, standard deviation=1) ,

import random
import numpy as np
x = np.random.randn()
y = np.random.randn(3)
z = np.random.randn(3, 3)
print(x, type(x))
print(y, type(y))
print(z, type(z))

11. np.random.standard_normal(size=()): Returns the probability density random number of the standard normal distribution (mean=0, standard deviation=1)

np.random.standard_normal(): returns the probability density random number of the standard normal distribution (mean=0, standard deviation=1), size defaults to None (returns 1 random number), and can also be an int or an array

import random
import numpy as np
x = np.random.standard_normal()
y = np.random.standard_normal(size=(3,3))
print(x, type(x))
print(y, type(y))

The results of np.random.rand() and np.random.standard_normal() are similar , both of which return random floating-point numbers or arrays that conform to the standard normal distribution.

12. np.random.randint(a, b, size=(), dtype=int): returns a random integer in the range [a, b) (containing repeated values)

np.random.randint(a, b, sizie=(), dytpe=int) - size defaults to None (returns 1 random number), and can also be int or array

import random
import numpy as np
# 从序列[0, 10)之间返回shape=(5,5)的10个随机整数(包含重复值)
x = np.random.randint(0, 10, size=(5, 5))
# 从序列[15, 20)之间返回1个随机整数(size默认为None, 则返回1个随机整数)
y = np.random.randint(15, 20)
print(x, type(x))
print(y, type(y))

13. random.seed() : Set random seed

After setting the random seed to 10, the random number of random.random() will be directly set to: 0.5714025946899135

import random
random.seed(10)
x = random.random()
print(x,type(x))
random.seed(10)
y = random.random()
print(y,type(y))
z = random.random()
print(z,type(z))

The random number is generated like this: We regard this complex algorithm (called a random number generator) as a black box, throw the seed we prepared into it, and it will return you two things, one is The random number you want, the other is a new seed that is guaranteed to generate the next random number, put the new seed into the black box, and get a new random number and a new seed, and then generate random numbers The road is getting farther and farther.

We use the following code to test:

import numpy as np
if __name__ == '__main__':
    i = 0
    while i < 6:
        if i < 3:
            np.random.seed(0)
            print(np.random.randn(1, 5))
        else:
            print(np.random.randn(1, 5))
        i += 1
    i = 0
    while i < 2:
        print(np.random.randn(1, 5))
        i += 1
    print(np.random.randn(2, 5))
    np.random.seed(0)
    print("###################################")
    i = 0
    while i < 8:
        print(np.random.randn(1,5))
        i += 1

 

Through this experiment we can get the following conclusions:

  • After using the random number seed twice, even after jumping out of the loop, the result of generating the random number is still the same. After jumping out of the while loop for the first time, enter the second while loop, and the two random arrays obtained are indeed different from those with random number seeds added. However, the result of adding random number seed in the latter is the same as the result in the previous eight cycles. Note that the random number seed has always had an impact on the subsequent results. At the same time, after the random number seed is added, the following random arrays are generated in a certain order .
  • The result of the sixth random number generation after the same random seed, the result of two arrays with five columns and two arrays with one row and five columns is the same. Note that when generating a multi-row random array, it is composed of a single-row random array .
  • Using the random number seed, the random numbers generated each time are the same, which means that the subsequent random numbers are generated in a certain order. When the random number seed parameter is 0 and 1, the random number generated is the same as the result I highlighted above. Description This parameter specifies the starting position of a random number generation. Each parameter corresponds to a position. And after the parameter is determined, the generation sequence of the following random numbers is also determined .
  • How to choose the parameters of the random number seed? I think it is random, this parameter is just to determine the starting position of the random number.

 


This article comprehensively refers to the following articles: 

icon-default.png?t=M4ADRandom Usage in Python %2522165352582116781685333907%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165352582116781685333907&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-2-119652905-null-null .142^v10^pc_search_result_control_group,157^v12^control&utm_term=python+random&spm=1018.2226.3001.4187 python random function_PandaDou's blog-CSDN blog_python random functionicon-default.png?t=M4ADhttps://blog.csdn.net/m0_37822685/article/details/80363530?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-80363-530-blog 119652905.pc_relevant_paycolumn_v3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-80363530-blog-119652905.pc_relevant_paycolumn_v3&utm_relevant_index=1 python常用random随机函数汇总,用法详解及函数之间的区别--One picture to understand python random functionicon-default.png?t=M4ADhttps://blog.csdn.net/weixin_45914452/article/details/115264053?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-015blog-2%7Edefault%7ECTRLIST%7Edefault-1-015b 110164241.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant_default&utm_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-115264053- blog -110164241.pc_relevant_default&utm_relevant_index= Blog_Random Seed icon-default.png?t=M4ADhttps://blog.csdn.net/qq_31511955/article/details/110424334

Guess you like

Origin blog.csdn.net/m0_62735081/article/details/124978101
Recommended