1.5: Random Numbers
- Page ID
- 122066
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