Generating random numbers is a task you meet almost daily while working as a developer in Python or any other programming language, especially object-oriented languages. Even as a beginner trying to practice and master the language, you will at one point need to generate simple random in your respective language. However, these might not be as complex as those that expert developers interact with daily.

The skill of randomness harnessing and generating random numbers is essential and a necessary skill that finds application in many modern fields. These range from artificial neural networks, machine learning, and stochastic gradient descent. In the latter, randomness is responsible for shuffling the dataset that is ideal for training. Randomness finds application in many applications, including lotteries, games, and other additional applications in need of the generation of random numbers.

Machine learning has various sources of randomness. In fact, randomness can be a vital tool to advance learning algorithms and build robust ones that will eventually lead to more accurate models and enhanced overall predictions.

The main core sources of randomness include:

- Randomness in Algorithms
- Randomness in data

In this article, we will concentrate on helping you understand how to generate random numbers in Python. We will explore the two main approaches to generating random numbers, including the NumPy library and the random module.

## Generating random numbers in Python

### Example 1: Generating random numbers between 1 and 50

import random for x in range(5): print(random.randint(1,50))

The code above prints five random integers between 1 and 50. It also indicates that the number of values to be printed is 5. If you choose to print five values, you change it to for x in range (5). The last line, print(random.randint(1,50)), generates a random number between 1 and 50 and prints it out on the console.

### Example 2: Random numbers between 1 and 50 with multiples of 10

In the code below, a random number between 1 and 50 will be generated. And then, the resultant value is then multiplied by 10. In this case, the highest value that can be printed is 50 * 10. The result is a multiple of 10.

import random for x in range(5): print(random.randint(1,50) *10) print()

### Pseudorandom Number Generators

A pseudorandom number generator is a mathematical trick that applies randomness to both algorithms and programs.

In Machine learning, pseudorandomness is used instead of true randomness. The latter requires a true source of randomness—for instance, a Geiger counter.

Pseudorandomness involves using a deterministic process to generate numbers that closely resemble the random ones. It is used in initializing coefficients with random values as well as data shuffling.

These programs work by involving a function that returns a random number when called and another novel random number when called again.

You can use wrapper functions to get randomness either as a floating point, for a certain distribution, a given range, or a particular integer.

There is a sequential generation of numbers. The deterministic nature of the sequence is also seeded with an initial number. On the off chance that the pseudorandom number generator is not seeded, it may use the time of the current system either in milliseconds or seconds as the seed.

The critical point is to ensure that the same process of seeding results in a similar random number sequence. So, you are at will to choose the value of the seed.

### Using the Random Library to generate Random Numbers in Python

A collection of functions is responsible for random numbers generated from the Python standard library module called random. On the other hand, Mersenne Twister is a robust and popular pseudorandom number generator.

Here, we use the standard Python API to generate various use cases of both generating and using random numbers as well as randomness.

### Seed the Random Number Generator

The parameter that is required by a pseudorandom number generator is called the seed. It is necessary to start the sequence. By being deterministic, we mean that if the function is given the same seed, then the same sequence of numbers will be produced every time.

The seed function will take an integer as an argument. By so doing, it will seed the pseudorandom number generator. The default for the current system in milliseconds from every epoch will be used if the seed() function is not called before using the randomness.

**Example 1: Seeding the pseudorandom number generator**

The example illustrates the generation of random numbers and illustrates how the reseeding generator results in a similar sequence of generated numbers.

from random import random from random import seed # random number generator seed seed(1) # random numbers generation print(random(), random(), random()) # seed reset seed(1) # andom numbers generation print(random(), random(), random())

The output consists of 3 random numbers, reseeds the generator, and indicates how the three random numbers are generated.

0.13436424411240122 0.8474337369372327 0.763774618976614

Further, necessary control is setting the seed to be certain that the code can produce similar results every time it is run before production.

A case where a different seed is applicable is a situation where randomization is a control mechanism for confounding variables. In such a case, every experimental run needs a varied seed value.

#### Random Floating-Point Values

The random() function is responsible for generating random floating-point values.

The resultant values have a distribution that is uniform which implies that every value has an equal opportunity.

These values are also generated in the range of between 0 and 1. And the specifics are an interval of (0, 1).

**Example 2: how to generate five random floating-point values**

from random import seed from random import random # random number generator seed seed(1) # random numbers generate (0-1) for i in range(5): value = random() print(value)

**Output**

After running the example above, each random floating-point value is printed as shown above:

You also have the option to rescale floating-point values if you so wish. To do so, you need to multiply the floating-point values by the new range’s size and subsequently adding the minimum value as illustrated below.

scaled_value = min + (value * (max - min))

In the case above, max refers to the maximum while min refers to the intended range’s minimum values. Besides, the randomly-generated floating-point value in the range of between 0 and 1 is the value.

#### Random Integer Values

The randint() function is necessary for the generation of random integer values. It takes the start and the end of the range for integer values generated as the arguments. In this scenario, both the end and start are included as part of the generated range values. In fact, it comes in the interval [start, end]. Thus, the uniform distribution is the source of random values

**Example 3: Generation of 10 random integer values between 0 and **10

from random import seed from random import randint # random number generator seed seed(1) # integers generation for i in range(10): val = randint(0, 10) print(val)

#### Random Gaussian Values

The gauss() function is handy in generating random floating-point values drawn from the Gaussian distribution.

The core parameters, i.e., the mean and the standard deviation, are the two corresponding parameters determining the distribution’s size.

According to the example below, where ten random values are generated, and its source is the Gaussian distribution, the standard deviation is 1.0, and the mean is 0.0.

It is critical to note that the parameters have no bounds on the values and how they spread. In fact, the shape of the distribution is the determining factor. This is proportionately above and below 0.0 in this case.

**Example : How to generate random Gaussian values**

from random import gauss from random import seed # random number generator seed seed(1) # Gaussian values generation for i in range(5): val = gauss(0, 1) print(val)

The 5 Gaussian random values are generated and printed after running the above example, as shown above.

#### Randomly selecting from a List

The choice() function is handy in implementing the behavior to engage random numbers to choose an item randomly from a list. The choosing is such that there is a uniform likelihood.

A scenario to consider is one of the lists of 20 integers with indexes between 0 and 19. In this case, you can generate a randomized number in the range of 0 to 19 and choose the item from the given list.

We illustrate this example below with five examples of selecting a single random item from the list given.

from random import seed from random import choice # random number generator seed seed(1) # sequence preparation sequence = [j for j in range(20)] print(sequence) # choose from the sequence for j in range(5): select =choice(sequence) print(select)

### Using the Numpy Library to generate Random numbers in Python

The Numpy library has several functionalities that generate random numbers. That is beside the mathematical operations it is very handy in.

**Random Floating-Point Values**

We will kick off the Numpy library by examining how to create random floating-point values. The NumPy function rand() is critical in generating a random array of floating-point values. The count of dimensions of the resultant array generated corresponds to the numbers indicated in the function rand().

On the off chance that there is no argument, then what is created is a single random value.

Example of generating ten random floating-point values array from a uniform distribution

# random floating point values generation from numpy.random import seed from numpy.random import rand # seed random number generator seed(1) # random numbers generate ( 0–1) val = rand(5) print(val)

#### Random Integer Values

The NumPy function randint() can generate random integers array. The function can accommodate three arguments that consist of the lower end and the number of integer values. The latter can also be referred to as the array’s size. The other argument is the upper end which is exclusive of the resultant range. On the other hand, the lower end is inclusive.

Example to illustrate the generation of 20 random integer values whose value should fall between 0 and 10 using the standard normal distribution.

# random integer values generation from numpy.random import seed from numpy.random import randint # random number generator seed seed(1) # integers generation val = randint(0, 10 , 20) print(val)

#### Random Gaussian Values

The NumPy function randn() is responsible for generating random Gaussian values. The standard Gaussian distribution is the source of the Gaussian values. Note that the distribution has a deviation of 1.0 and a mean of 0.0.

The standard normal distribution is represented using the red curve on the graph that follows. It has a standard deviation of 1 and a mean of 0.

from random import gauss from random import seed # random number generator seed seed(1) # Gaussian values generation for i in range(5): val = gauss(0,1) print(val)

#### Shuffle NumPy Array

The NumPy function shuffle() can shuffle a NumPy array in place. A list of 20 integer values is generated initially, subsequently shuffled, and printed in the example presented below.

from numpy.random import seed from numpy.random import shuffle # random number generator seed seed(1) # sequence preparation seq = [j for j in range(20)] print(seq) # randomly shuffle the sequence shuffle(seq) print(seq)

### Common Random Number Operations in Python

#### uniform(x,y )

The uniform(x, y) function is responsible for floating-point random number generation between the values presented as the arguments. It has a lower limit and the upper limit. Note that the lower limit is included in the generation, while the upper limit is not included.

# list initialization _list =[1, 4, 5, 10, 2] # printing list before shuffling print(“\nList before shuffling: ”, end =” ”) for j in range(0, len(_list)): print(_list[j], end=” ”) # use function shuffle() to shuffle the list random.shuffle(_list) # print the list after shuffling print(“\nList after shuffling is : ”, end=” ”) for j in range(0, len(_list)): print(_list[j], end=” ”) print(“\n Random floating point number between 5 and 10: ”, end=” ”) print(random.uniform(5, 10))

#### shuffle()

The function shuffle() is responsible for shuffling a list or a sequence for that matter in place. Also, note that shuffling simply refers to changing the position of elements in the given sequence, as shown below.

import random # List declaration test_list =[‘A,’ ‘B’, ‘C’, ‘D’, ‘E’] print(“original list :”) print(test_list ) # 1 shuffle random.shuffle(test_list) print(“\nafter shuffle 1: ”) print(test_list) # 2 shuffle random.shuffle(test_list) print(“\nafter shuffle 2: ”) print(“test_list”)

#### seed()

The seed() function saves a random function’s state to randomly allow the generation of numbers when the code is executed multiple times. This can happen on varied machines or the same machine. However, it has to be for a specified seed value.

The previous value number that is generated by the generator is what we are calling the seed value. Further, remember that the current system time is used in case of the first time when there is no previous value.

Import random print(“random number between 0 and 1: ”, end=” ”) print(random.random()) # random number seeding using seed() random.seed(3) print(“mapped random number with 3 is :”, end=” ”) print(random.random()) # using seed() to seed different random number random.seed(5) print(“mapped random number with 3 is: ”, end =” ”) print(random.random()) # using seed() to seed to 3 once more random.seed(3) print(“mapped random number with 3: ”, end =” ”) print(random.random()) # using seed() to seed to 5 again random.seed(5) print(“mapped random number with 5: ”, end=” ”) print(random.random())

#### random()

The random() function is responsible for generating a float random number that is either greater or equal to 0, and it must be less than 1.

import randomization print(“random number between 0 and 1: ”, end=””) print(random.random())

#### randrange(beg, end, step)

The function randrange() from the random module is useful in generating random numbers given specific ranges. Also, it includes the use of steps as a parameter.

Import random # generate a random number using choice() from a given list of numbers. Print(“\nrandom number from list is: ”, end =” ”) print(random.choice([1,4,8,10,3])) # using randrange() to generate in the range from 10 to 30. # The last parameter 2 is step size to skip 2 numbers when choosing. print(“\nrandom number from range: ”, end =” ”) print(random.randrange(10,30,2))

#### choice()

The function choice returns a random value or item from a string, a tuple, or a list. Besides, choice() is an inbuilt function in Python.

Import random # random value is printed from the list _list =[1,2,3,4,5,6] print(random.choice(_list)) # random item is printed from the string _str = ”soldier” print(random.choice(_str))

## Summary

This article was all about generating and working with random numbers in Python. The random module also has quite a large set of methods, each handling a specific function. For instance, the getstate() function is responsible for returning the random number generator’s internal state at a given time.

For more details on the methods available, you need to go through the entire random module and find out what applies to your scenario. Because not all of them can be used at the same time.

The key takeaways include:-

- Generation of random numbers array using the Numpy Library
- Generation of random numbers and general use of randomness through Python Standard Library
- Pseudorandom number generators can apply randomness in programs