Python study notes -- use of random library

basic random number function

seed()

Used to set the random number seed, the default is the system time as the seed

#默认以系统时间为种子
random.seed()
for i in range(5):
    print(random.random())

first run results

0.26734155407208104
0.42545661328469664
0.9117954845687343
0.24536621387699853
0.4507611579106827

second run results

0.2224361976810766
0.5394607691574935
0.6576528924236562
0.37023121607844
0.47283418395156696

The random numbers generated by each running result are different, indicating that by default, the random numbers generated with the system time as the seed are difficult to reproduce

import random
#设定随机数种子为10
random.seed(10)
#产生随机数
for i in range(5):
    print(random.random())

operation result

0.5714025946899135
0.4288890546751146
0.5780913011344704
0.20609823213950174
0.81332125135732

No matter how many times you run it, the above results are the same, indicating that the random numbers generated by artificially set seeds can be reproduced

Extended Random Number Function

randint(a,b)

Generate an integer between [a,b]

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

randrange(m,n[,k])

Generate a random integer between [m,n] with a step size of k

import random
#生成[10,100]之间步长为10的整数
r=random.randrange(10,100,10)
print(r)

jagged bits(k)

Generate a k-bit long random integer

import random
r=random.getrandbits(16)
print(r)

operation result

63811

uniform(a,b)

Generate a random decimal between [a,b]

import random
r=random.uniform(10,100)
print(r)

operation result

40.33708598015649

choice(seq)

Randomly select an element from the sequence seq

import random
r=random.choice([1,2,3,4,5,6,7,8,9])
print(r)

operation result

5

shuffle(seq)

Randomly arrange the elements in the sequence seq, and return the scrambled sequence

import random
s=[1,2,3,4,5,6,7,8,9]
random.shuffle(s)
print(s)

operation result

[8, 3, 5, 7, 9, 1, 6, 2, 4]

Guess you like

Origin blog.csdn.net/weixin_51627036/article/details/122560050