# 1.5: Random Numbers

$$\newcommand{\vecs}{\overset { \rightharpoonup} {\mathbf{#1}} }$$ $$\newcommand{\vecd}{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}}$$$$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$$$\newcommand{\AA}{\unicode[.8,0]{x212B}}$$

Random numbers are part of the NumPy package. For example, if we want to create 5 random numbers in $$(0,1)$$, we use the following.

import numpy as np
print(np.random.rand(5))


output: [0.99332819 0.98682806 0.32328937 0.70417298 0.59908967]

Using the same function above, together with the matplotlib package, we can create a histogram of 100000 real numbers (with 50 bins) with the following code to see the distribution.

import numpy as np
import matplotlib.pyplot as plt

y = np.random.rand(10**5)
plt.hist(y, 50);
plt.show()


output: If, instead, we wanted a normal distribution, we can use the randn function.

import numpy as np
import matplotlib.pyplot as plt

y = np.random.randn(10**5)
plt.hist(y, 50);
plt.show()


output: #### Random Package

For a bit more flexibility with random numbers, we can use Python's random package. This allows us to use, for example, the randint function to give us a random integer between two numbers, inclusive. We do so here:

import random
x=random.randint(1,5)
print(x)


output:    3

1.5: Random Numbers is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.