python--Random library

Random library
From random import *
Decimals between k=random()[0)
print(k)
Re:0.04559362245524701
Re:0.3406472808823092

k=randint(1,4) generates an integer between 1 and 4, which can be taken to 4

a=getrandbits(4) generates an integer between 0000-1111 (binary) and similarly if k=5,00000-11111

b=randrange(1,25,2) generates an arithmetic sequence and then either returns a number, excluding 25, 2 is an arithmetic difference

c=uniform(1,4) random decimal between [1,4]

list=['1',2,[3,4],33]
d=choice(list) returns any element in the list
Re:[3, 4]

list=['1',2,[3,4],33]
Note that shuffle(list) does not use the return value, but directly changes the order of the elements in the list
print(list)
Re:[[3, 4], 33, 2, '1']

list=['1',2,[3,4],33]
e=sample(list,2) returns any k elements in the list type (not just the list type), but the return result is the list type
Re:[[3, 4], '1']

Seed (a) As long as the selected seed calls the random function above, the result will not change, but if it is empty, it will still change

Example 1. 10 integers within 100
list=range(1,101)
a=sample(list,10)
print(a)
Re:[68, 13, 71, 26, 80, 19, 15, 5, 39, 10]
Example 2. Odd numbers within 100 are returned randomly
a = randrange (1,100,1)
print(a)

Monte Carlo seeking pi
N=122228
c=0
for i in range(N):
    x,y=uniform(0,1),uniform(0,1)
    if (x**2+y**2)<=1:
        c=c+1
pi=(c/(N))*4
print(pi)
 
Re:3.149851097948097

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325179063&siteId=291194637