Saturday 5 December 2015

Python: Generate random numbers

Python provides random module to generate random numbers, By using random.seed method you can initialize the random generator.

random.seed(a=None, version=2)
Used to initialize random generator. If you don’t specify value for a, then system time is used by default. ‘a’ can be int, string.

If version=1, then hash of ‘a’ is used for initialization, if version=2 a str, bytes, or bytearray object gets converted to an int and all of its bits are used.  

Following methods are used to generate random number and shuffle list randomly in python.

Method
Description
random.getrandbits(k)
Returns an integer with k random bits.
random. randrange(a, b)
Returns an integer in the range [a, b).
random.randint(a, b)
Return a random integer N such that a <= N <= b. It is equivalent to random. randrange(a, b+1)
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
random.shuffle(list)
Shuffles a list in-place, i.e. permutes it randomly
random.random()
Return the next random floating point number in the range [0.0, 1.0).
random.uniform(a, b)
Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
random.triangular(low, high, mode)
Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

Note

os.urandom(n): Return a string of n random bytes suitable for cryptographic use.
>>> import random
>>> 
>>> random.getrandbits(20)
700469
>>> random.getrandbits(10)
216
>>> 
>>> random.randrange(-10000, 234567)
160279
>>> random.randrange(-10000, 234567)
163448
>>> random.randrange(-10000, 234567)
141854
>>> random.randrange(-10000, 234567)
113743
>>> 
>>> 
>>> random.choice(list(range(10, 1000)))
448
>>> random.choice(list(range(10, 1000)))
459
>>> 
>>> random.choice([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
12
>>> random.choice([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
10
>>> random.choice([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
20
>>> random.choice([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
8
>>> 
>>> list=[2, 4, 6, 8, 10]
>>> random.shuffle(list)
>>> list
[8, 4, 2, 6, 10]
>>> 
>>> random.uniform(0, 10)
4.136505113937443
>>> random.uniform(0, 10)
7.627400639276029
>>> random.uniform(0, 10)
8.812919559259498





Previous                                                 Next                                                 Home

No comments:

Post a Comment