Python random Module
Python random The module is mainly used to generate random numbers.
random The module implements pseudo-random number generators for various distributions.
To use random function must be imported first:
import random
View the contents of the random module:
Example
import
random
dir
(
random
)
[
'BPF'
,
'LOG4'
,
'NV_MAGICCONST'
,
'RECIP_BPF'
,
'Random'
,
'SG_MAGICCONST'
,
'SystemRandom'
,
'TWOPI'
,
'_Sequence'
,
'_Set'
,
'all'
,
'builtins'
,
'cached'
,
'doc'
,
'file'
,
'loader'
,
'name'
,
'package'
,
'spec'
,
'_accumulate'
,
'_acos'
,
'_bisect'
,
'_ceil'
,
'_cos'
,
'_e'
,
'_exp'
,
'_floor'
,
'_inst'
,
'_log'
,
'_os'
,
'_pi'
,
'_random'
,
'_repeat'
,
'_sha512'
,
'_sin'
,
'_sqrt'
,
'_test'
,
'_test_generator'
,
'_urandom'
,
'_warn'
,
'betavariate'
,
'choice'
,
'choices'
,
'expovariate'
,
'gammavariate'
,
'gauss'
,
'getrandbits'
,
'getstate'
,
'lognormvariate'
,
'normalvariate'
,
'paretovariate'
,
'randbytes'
,
'randint'
,
'random'
,
'randrange'
,
'sample'
,
'seed'
,
'setstate'
,
'shuffle'
,
'triangular'
,
'uniform'
,
'vonmisesvariate'
,
'weibullvariate'
]
Next we use the random() method to return a random number in thehalf-open interval [0,1), which includes 0 but excludes 1.
Example
Import the random package
import
random
Generate a random number
(
random
.
random
(
)
)
The output of the above example is:
0.4784904215869241
seed() The method changes the seed of the random number generator; call it before calling other random module functions.
Example
#!/usr/bin/python3
import
random
random
.
seed
(
)
(
"Random number generated with the default seed:"
,
random
.
random
(
)
)
(
"Random number generated with the default seed:"
,
random
.
random
(
)
)
random
.
seed
(
10
)
(
"Random number generated with integer seed 10:"
,
random
.
random
(
)
)
random
.
seed
(
10
)
(
"Random number generated with integer seed 10:"
,
random
.
random
(
)
)
random
.
seed
(
"hello"
,
2
)
(
"Random number generated with a string seed:"
,
random
.
random
(
)
)
Running the example above produces:
使用默认种子生成随机数: 0.7908102856355441
使用默认种子生成随机数: 0.81038961519195
使用整数 10 种子生成随机数: 0.5714025946899135
使用整数 10 种子生成随机数: 0.5714025946899135
使用字符串种子生成随机数: 0.3537754404730722
random module methods
The random module methods are as follows:
| Method | Description |
|---|---|
| seed() | Initialize the random number generator |
| getstate() | Return an object capturing the generator's current internal state. |
| setstate() | state should have been obtained from a previous call to getstate(), and setstate() restores the generator's internal state to what it was when getstate() was called. |
| getrandbits(k) | Return a non-negative Python integer with k random bits. This method is supplied with the MersenneTwister generator, and some other generators may also provide it as an optional part of their API. Where possible, getrandbits() enables randrange() to handle arbitrarily large ranges. |
| randrange() | Return a randomly selected element from range(start, stop, step). |
| randint(a, b) | Return a random integer N such that a <= N <= b。 |
| choice(seq) | Return a random element from the non-empty sequence seq. If seq is empty, IndexError is raised. |
| choices(population, weights=None, *, cum_weights=None, k=1) | Return a list of k elements chosen from population with replacement. If population is empty, IndexError is raised. |
| shuffle(x[, random]) | Shuffle the sequence x in place. |
| sample(population, k, *, counts=None) | Return a k-length list of unique elements chosen from a population sequence or set. Used for random sampling without replacement. |
| random() | Return the next random floating-point number in the range [0.0, 1.0). |
| uniform() | Return a random floating-point number N such that a <= N <= b when a <= N <= b; when b < a, then b <= N <= a 。 |
| triangular(low, high, mode) | Return a random floating-point number N such that low <= N <= high, and use the specified mode between these boundaries. The low and high boundaries default to zero and one. The mode parameter defaults to the midpoint between the boundaries, giving a symmetric distribution. |
| betavariate(alpha, beta) | Beta distribution. The conditions on the parameters are alpha > 0 and beta > 0. Return values range between 0 and 1. |
| expovariate(lambd) | Exponential distribution. lambd is 1.0 divided by the desired mean; it should be non-zero. |
| gammavariate() | Gamma distribution (not the gamma function). The conditions on the parameters are alpha > 0 and beta > 0. |
| gauss(mu, sigma) | Normal distribution, also called the Gaussian distribution. mu is the mean and sigma is the standard deviation. This function is slightly faster than the normalvariate() function defined below. |
| lognormvariate(mu, sigma) | Log-normal distribution. If you take the natural logarithm of this distribution you get a normal distribution with mean mu and standard deviation sigma. mu can be any value; sigma must be greater than zero. |
| normalvariate(mu, sigma) | Normal distribution. mu is the mean, sigma is the standard deviation. |
| vonmisesvariate(mu, kappa) | von Mises distribution. mu is the mean angle, expressed in radians, between 0 and 2pi; kappa is the concentration parameter and must be greater than or equal to zero. If kappa equals zero, the distribution reduces to a uniform random angle in the range 0 to 2pi. |
| paretovariate(alpha) | Pareto distribution. alpha is the shape parameter. |
| weibullvariate(alpha, beta) | Weibull distribution. alpha is the scale parameter and beta is the shape parameter. |