Python study notes (8) -- the use of random library

Pseudo-random number: Elements in a pseudo-random sequence generated by the Mersenne rotation algorithm

Use random library

1. Basic random function

Random numbers need a seed, according to which a fixed sequence of random numbers is generated through Mersenne rotation algorithm.
seed (a=None) Initializes the given random number seed, defaults to the current system time

random() generates a random decimal between [0.0, 1.0)

>>> import random
>>> random.seed(5)
>>> random.random()
0.6229016948897019
>>> random.random()
0.7417869892607294
>>> random.seed(5)
>>> random.random()
0.6229016948897019

The use of seed is mainly used in some systems. According to this random seed, the problem can be reproduced. If the seed is not used, the default is the time with high accuracy of the current system, which cannot be reproduced.

2. Extended random function

randint(a,b) generates an integer between [a,b]

randrange(m,n[,k]) generates a random integer between [m,n) with k steps

getrandbits(k) generates a random integer of k bits long

uniform(a,b) generates a random decimal between [a,b]

choice(seq) randomly selects an element from the sequence seq

shuffle(seq) Randomly arrange the elements in the sequence seq and return the shuffled sequence

>>> random.randint(0,100)
94
>>> random.randrange(0,100,10)
50
>>> random.uniform(0,100)
69.04468457583359
>>> random.getrandbits(16)
52113
>>> random.choice([1,2,3,4,5,6,7])
7
>>> s=[1,2,3,4,5,6,7]
>>> random.shuffle(s)
>>> s
[4, 3, 5, 7, 2, 1, 6]

3. PI calculation problem

The calculation of pi, in addition to using a complex mathematical formula, can also simulate the original calculation method of pi by the Monte Carlo method. The Monte Carlo method refers to randomly scattering particles in the square where the circle is located, then counting the number of particles in the circle, and then calculating the area of ​​the circle, or the pi. So now that the computer is smart, we can simulate random particles through the computer to calculate the pi. code show as below:

#getPi.py
from random import random
from time import perf_counter
DARTS = 1000*1000
hits=0.0
start=perf_counter()
for i in range(1,DARTS):
     x, y = random(),random()
     dist = pow(x**2 + y**2, 0.5)
     if dist <= 1.0:
           hits +=1
pi = 4 *(hits/DARTS)
print( " Pi is: {} " .format(pi))
print( "The running time is: {:.5f}s " .format(perf_counter() - start))

 

Guess you like

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