## [Python] Random module learning

When generating random numbers with python, the random module definitely comes to mind. The random module implements pseudo-random (Pseudo-Random) number generation for various distributions. This time we will learn the random module of Python.

For integers, the random module is very simple, and this is also a very common method of pseudo-random generation; but for sequences, the random module can randomly select sequence elements, generate random distribution of sequences, or random non-repetitive sampling, etc. .

The distribution implemented by the random module mainly includes: uniform, normal (Gaussian), lognormal, negative exponential, gamma, beta, etc.; there is also a von Mises, which is to generate an angular distribution, the algorithm idea can refer to wiki: http://en.wikipedia .org/wiki/Von_Mises_distribution .

In the random module, the following constants are defined:

Python code
1. NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
2. TWOPI = 2.0 * _pi
3. LOG4 = _log(4.0)
4. SG_MAGICCONST = 1.0 + _log(4.5)
5. BPF = 53        # Number of bits in a float
6. RECIP_BPF = 2**-BPF

Let's first look at the methods defined by the random module:

Python code
1. >>> import random;
2. >>> for method in dir(random):
3. ...   print method;
4. ...

Three classes are defined:

Python code
1. Random：
2. SystemRandom：
3. WichmannHill ：

These three classes can generate random numbers, among which Random is a commonly used random number generation algorithm. The random number generation we mainly discuss is the method of this class; WichmannHill and SystemRandom both inherit the Random class, and the random method of WichmannHill uses and Random class is similar to the random method. This algorithm mainly depends on the seed value. Interested students can look at the theory. I think the implementation is not difficult, but the theoretical estimate is a bit difficult; SystemRandom uses the random generation function of the operating system, such as unix Depends on /dev/urandom, windows depends on CryptGenRandom, etc.

Let's take a look at the methods provided by the random module:

Python code
1. random.seed([x])：

Set the seed value of the random package. This value is very important for generating random numbers. If you do not set it, the system time will be taken by default.

Python code
1. random.random()

Returns a random number, the value range is [0.0, 1.0), this method appears many times in the following distributions, so the random number generation algorithm is the basis of the random module. Let's take a look at the source code of the random function:

Python code
1. def random(self):
2.    x, y, z = self._seed
3.    x = (171 * x) % 30269
4.    y = (172 * y) % 30307
5.    z = (170 * z) % 30323
6.    self._seed = x, y, z
7.    return (x/30269.0 + y/30307.0 + z/30323.0) % 1.0

The implementation of the algorithm looks simple. If you want to understand the principle of this random number algorithm in depth, you can refer to the article An efficient and portable pseudo-random number generator (Applied Statistics 31 (1982) 188-190), the algorithm implementation behind the article The source code of random is slightly different. The article is referred to here: http://www2.imperial.ac.uk/~hohs/S9/2007-2008/wichmannhill.pdf

Python code
1. random.expovariate(lambd)

index distribution

Python code
1. random.gammavariate(alpha, beta)

Gamma distribution, requires alpha>0 and beta>0, note that this is not a Gamma function. Of course, the Gamma function is used in the calculation process. For more information on Gamma distribution refer to the wiki: http://en.wikipedia.org/wiki/Gamma_distribution

Python code
1. random.gauss(mu, sigma)
2. random.normalvariate(mu, sigma)

These two are generated Gauss distributions, and the two are generated using different ideas. The former uses statistical calculations, and the latter is generated according to the standard normal distribution definition. The former generation speed is even faster, but in multi-threaded scenarios, you need to lock and control concurrency by yourself.

Python code
1. random.lognormvariate(mu, sigma)：

Normal distribution at log level.

Python code
1. random.betavariate(alpha, beta)

Beta Distribution, which requires alpha>0 and beta>0, depends on the gamma distribution and is generated by the gamma distribution function.

Python code
1. random.triangular(low, high, mode)

Generate a triangular distribution function, see http://en.wikipedia.org/wiki/Triangular_distribution for details on Triangular Distribution , and there are more detailed discussions in the wiki; looking at the source code, you will find that the generation of this function also depends on the random() function.

Python code
1. random.uniform(a, b)

Generates a uniform distribution of [a,b], which uses the random() function, and actually produces a value of a+(ba)*random()

Python code
1. random.paretovariate(alpha)：Pareto Distribution
2. random.vonmisesvariate(mu, kappa): Von Mises Distribution, which is the distribution for angles.
3. random.weibullvariate(alpha, beta)：Weibull Distribution<span> </span>

These three distributions are slightly professional, and they are not used very often.

Applying Python to Sequence, you can see the effect of the following functions

Python code
1. random.choice(seq)
2. random.sample(population, k)
3. random.shuffle(x[, random])

The choice function randomly selects an element from seq, the sample function selects k unique elements from the element list, and the shuffle function randomly arranges the element list. Take a look at the example below:

Python code
1. >>> bits=['a','b','c','d','e','f','g']
2. >>> random.choice(bits)
3. 'a'
4. >>> random.choice(bits)
5. 'c'
6. >>> random.sample(bits,3)
7. ['c', 'b', 'e']
8. >>> random.sample(bits,3)
9. ['g', 'a', 'c']
10. >>> random.shuffle(bits)
11. >>> bits
12. ['a', 'f', 'd', 'g', 'b', 'e', 'c']

Python code
1. random.random()
2. random.randrange (stop)
3. random.randrange (start, stop [, step])
4. random.randint(a, b)
5. random.getrandbits(k)<span> </span>

The random function generates a random number of [0.0, 1.0), which is mentioned above; the randrange function is randomly selected in the mentioned range (start, end, step); the randint function is selected in [a, b], Note that both sides are closed intervals; the getrandbits function actually controls at the bit level, controlling the amount of randomness on each bit.

Python code
1. >>> random.random()
2. 0.6216895046152143
3. >>> random.randrange (10)
4. 7
5. >>> random.randrange (5,10)
6. 9
7. >>> random.randrange (5,10)
8. 6
9. >>> random.randrange (5,10)
10. 7
11. >>> random.randrange (5,10)
12. 5
13. >>> random.randrange (5,10,2)
14. 5
15. >>> random.randrange (5,10,2)
16. 9
17. >>> random.randrange (5,10,2)
18. 7
19. >>> random.randint(1,100)
20. 49
21. >>> random.randint(1,100)
22. 22
23. >>> random.getrandbits(5)
24. 27
25. >>> random.getrandbits(5)
26. 27
27. >>> random.getrandbits(5)
28. 7
29. >>> random.getrandbits(50)
30. 259336269183598
31. >>> random.getrandbits(500)
32. 2123294400168802339423947306484820684208555438132242308767915648686014450077945137455581839262813894933829601172344940098461036686745618482209213922214
33. >>> random.getrandbits(5000)
34. 4034754137539484179299467597527391507546381474148526154395421207380075606134559180138703425120094793323534549803288574253400061961405474748312233157619180389178319042116709667737968426875719453232825587709299171195574278743656906955409390042725992518977600085740467686975785820692459295094963664868994212901792068886664992509467663579527691907093450609832530263379958186539108800219479153927035711354075963574379567702705107895056023508996779148121923936388548341378859868882424925192771844170677816283953086457527992241139927429905498724725234373412588522642913731667566323782617498119281849336962492061749751663018412752756985945190973968626062918960920916813960732895100632389147211487593464557043805295027860687336511022864551102551287702441650416601162438483314529829096068674259579299557425952074299390480479779787510272694343411355085195312144186003575867190677050695130041384874117375485556935211062489182801151796266461330635349790915122810079710159825931951294785611281623200060903422400093055307371277330083371368887743322247273016355323686859209112857576218973944225428147564652781736490029302922410573312453153416182209839876163339188176414458934726982720923448475009661073041932910018380017325457354357313544645084438508127883399927917698522570586118494954794329286952111267534963812167557444992442451658941414640398737575936221194957286718271011604437241627690160697999192659641775460024935972380618868777518058797753473526196799809754689345865056290961953738953134889706900308020180214258  4225428147564652781736490029302922410573312453153416182209839876163339188176414458934726982720923448475009661073041932910018380017325457354357313544645084438508127883399927917698522570586118494954794329286952111267534963812167557444992442451658941414640398737575936221194957286718271011604437241627690160697999192659641775460024935972380618868777518058797753473526196799809754689345865056290961953738953134889706900308020180214258  4225428147564652781736490029302922410573312453153416182209839876163339188176414458934726982720923448475009661073041932910018380017325457354357313544645084438508127883399927917698522570586118494954794329286952111267534963812167557444992442451658941414640398737575936221194957286718271011604437241627690160697999192659641775460024935972380618868777518058797753473526196799809754689345865056290961953738953134889706900308020180214258  58  58

Python code
1. random.getstate()
2. random.setstate(state)<span> </span>

state is a state representation inside the random package, represented by an array of [VERSION,_seed, gauss_next], if you want to set state, please set VERSION to 1

Python code

Random maintains the process of generating random numbers internally. The jumpahead function resets the function generation process, so that the next random function can be generated in the same state without being affected by the random numbers that have already been generated. This function has little effect in the case of a single thread, but for multiple threads, it can control the initial state of random number generation in each thread to be consistent. There is a post on stackoverflow http://stackoverflow.com/questions/2546039/how-should-i-use-random-jumpahead-in-python that explains this problem in more detail, when using random numbers in multi-threaded situations The problem that needs this is also mentioned in the following post, you can look at it in detail.

The content provided by the random package is quite rich. In addition to generating random numbers, the operation of Sequence can also reduce the workload, especially the functions provided by the choice, sample, and shuffle functions.

Now that the random function is mentioned, let's understand the generation of the random function in depth. As mentioned earlier, the generation of random under the Unix system depends on /dev/urandom. In fact, another file that generates random numbers is /dev/random. The principle of the random numbers generated by the two is to use the entropy pool of the current system to calculate a fixed number of random bits, and then return these bits as a byte stream. The entropy pool is the environmental noise of the current system. Entropy refers to the degree of chaos in a system. System noise can be evaluated by many parameters, such as memory usage, file usage, the number of different types of processes, and so on. The difference between the two is that the latter will block (block) when it cannot generate random numbers, while the former will not. So using /dev/random is slower than using /dev/urandom to generate random numbers, but the randomness is better. If the requirements for using random numbers are not particularly high, /dev/urandom generates random numbers enough.

The learning of the random number random module of python is over. Be sure to distinguish between the random module and the Random class here. The latter is a class defined in the random module. To be precise, the methods provided in the random module are all methods in the Random class; if you want to use the SystemRandom and WichmannHill classes, you need to initialize them yourself

### Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325839615&siteId=291194637
Recommended
Ranking
Daily