Skip to content

How to generate random numbers in Python?

Randomness plays an important role in the evolution of machine learning algorithms. Python defines a set of functions that are used to generate or manipulate random numbers. This particular type of functions are used  in random initialization of weights in an artificial neural networks, splitting of data into random train and test sets, games, lotteries or any application requiring random number generation.

In this article, you will learn how to generate and work with random numbers in Python.

1. choice() function

import random 
print (random.choice([1, 4, 8, 10, 3])) 

2. randrange(beginning, end, step) :- This function is also used to generate random number but within a range specified in its arguments. 

# using randrange() to generate in range from 10 
# to 50. The last parameter 2 is step size to skip 
# two numbers when selecting.
print (random.randrange(10, 50, 3))

3. Random floating numbers using random() and seed() functions

# random number generator using seed
from random import seed
from random import random
# seed random number generator
seed(1)
# generate some random numbers
print(random())
# reset the seed
seed(2)
# generate some random numbers
print(random())

Output:

0.8474337369372327
0.1238327648331623

4. Random Integer numbers using randint() function

value = randint(0, 10)
	print(value)

5. Random Gaussian numbers using gauss() function

value = gauss(0, 1)
	print(value)
See also  Creating Interactive Corona Virus(COVID-19) Tracking Dashboard using Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.