Random Number Generation in Python Programming
Random number generation is the process of generating a number that cannot be predicted better than by a random chance.
Most computer generate pseudo random numbers which are not true random numbers. They use algorithms to generate random numbers.
Python uses Mersenne Twister algorithm for random number generation. In python pseudo random numbers can be generated by using random module.
Code for Random Numer Generation
from random import *print random()
Output: It will generate a pseudo random floating point number between 0 and 1.
from random import *print randint(10, 100)
Output: It will generate a pseudo random integer in between 10 and 100
from random import *print uniform(1, 10)
Output: It will generate a pseudo random floating point number between 1 and 10.
import randomlist = [‘1’,’4',’7',’Hi’]print random.choice(list)
Output: It will output any of the four objects in the list randomly.
import randomlist = [1,2,3,”4", “l90”, “hi”]random.shuffle(list)print (list)
Output: It will shuffle the list and randomly and print the shuffled list.
import randomfor i in xrange(5):print random.randrange(0, 100, 2)
Output: It will display 5 random numbers from range 0 to 100. 2 is the step need to be added into randomness. The syntax is random.randrange( start, stop, step )
import randomstr = “helloworld”list = [‘a’,’b’,’c’,’d’,’e’,’f’,’o’,’l’]print random.sample(str, 4)print random.sample(list, 4)
Output: It will output a list of 4 random characters from string and list. The syntax is random.sample (sequence, length)
Sample output:
['o', 'h', 'l', 'w']
['f', 'b', 'c', 'a']
Generate Random Number Using Seed
A seed is a number that is used to initialize a pseudo random number generator. Seed guarantees that if you start from same seed you will get the same sequence of random numbers.
import random
random.seed(5)
print(random.random())
print(random.random())
print(random.random())
Output:
0.62290169489
0.741786989261
0.795193565566
List of Functions in Python Random Module
seed(a=None, version=2):
Initialize the random number generator getstate() Returns an object capturing the current internal state of the generator.
setstate(state):
Restores the internal state of the generator.
getrandbits(k):
Returns a Python integer with k random bits.
randrange(start, stop[, step]):
Returns a random integer from the range.
randint(a, b):
Returns a random integer between a and b inclusive.
choice(seq):
Return a random element from the non-empty sequence.
shuffle(seq):
Shuffle the sequence.
sample(population, k):
Return a k length list of unique elements chosen from the population sequence.
By the following methodologies & code you will achieve a successful random number generation.
If you want to know more about random number generation then click here.
This Article is sourced from: mindmajix