Random numbers in Python
I use the random module to extract random numbers in the Python language. The library contains several random number generators.
import random
How to generate a random number
This function is a random generator that extracts an integer between the included start and end values.
random.randint(start, end)
Example
This script extracts a random number from 0 to 10.
>>> random.randint(0,10)
One of the possible results is the following:
>>> 2
The methods of the random module
The random module has many other useful features.
- betavariate(alfa,beta)
Generate a random number in the beta distribution. - choice(seq)
Select a random element in a sequence.
>>> seq=[1,2,3,4,5]
>>> random.choice(seq)
2 - choices(population, weigth=none, *, cum_weigths=none, k=1)
Select k elements from a population with reintegration.>>> seq=["a","b","c","d","e"]
>>> random.choices(seq,k=3)
['a', 'c', 'e'] - expovariate(lambd)
Generate a random number in an exponential distribution. - gammavariate(alfa, beta)
Generate a random number in a gamma distribution. - gauss(mu, sigma)
Generate a random number in a Gaussian distribution. - getrandbits(k)
Generate an integer random number with k bits.
>>> random.getrandbits(3)
4 - getstate()
Returns the internal status. - lognormvariate(mu, sigma)
Generate a random number in a normal logarithmic distribution. - normalvariate(mu, sigma)
Generate a random number in a normal distribution. - paretovariate(alpha)
Generate a random number in a Pareto distribution. - randint()
Generate a random integer from x to y (inclusive).
>>> random.randint(0,10)
2 - random()
Generate a random number from 0 to 1.>>> random.random()
0.5357514603916116 - randrange( x, y [,step] )
Generate a random number from x to y (excluded) with step step equal to one of default.>>> random.randrange(0,10)
7 - sample( population, k )
Select k elements of a population without repetitions.>>> random.sample(["a", "b", "c"], 2) ['c', 'a']
- seed(a=None, version=2)
Initializes the internal status. - setstate(state)
Restores the internal state of an object. - shuffle( population )
Change the order of items in a population.>>> x=[1,2,3,4,5,6,7,8,9,10]
>>> random.shuffle(x)
>>> x
[8, 5, 6, 1, 3, 10, 7, 9, 4, 2] - triangular(low=0.0 , high=1.0, mode=None)
Generate a random number in a triangular distribution. - uniform(x, y)
Generate a real random number in the range (a,b).>>> random.uniform(0,4)
1.940039451527575 - vonmisesvariate(mu, kappa)
Generate a random number in a circular data distribution. - weibullvariate(alpha, beta)
Generate a random number in a Weibull distribution.