Skip to main content
Mathematics LibreTexts

1.5: Random Numbers

  • Page ID
    122066
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\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]{\| #1 \|}\) \( \newcommand{\inner}[2]{\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]{\| #1 \|}\) \( \newcommand{\inner}[2]{\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:

    clipboard_e98103572113ae9ec1ffbe2439678ec4b.png

    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:

    clipboard_e97a3d683dbff7ac45b619ffe8f3ff121.png

    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.

    • Was this article helpful?