4.6. Examples: Lecture 4#

4.6.1. Use of `random ()` and `randint ()`#

  • random_01.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra 0 ed 1
python3 random_01.py 10
'''

import sys
import random

def main () :
    '''
    Funzione che implementa il programma principale
     - documentazione di random https://docs.python.org/3/library/random.html
    '''

    if len(sys.argv) < 2 :
        print ('usage: ', sys.argv[0], 'numero')
        exit ()

    randlist = []
    for i in range (int (sys.argv[1])):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (random.random ())
        print (i, randlist[-1])


    randlistint = []
    for i in range (int (sys.argv[1])):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlistint.append (random.randint (0, 100))
        print (i, randlistint[-1])


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.2. Use of `random.seed ()`#

  • random_02.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra 0 ed 1
a partire da un determinato seed
python3 random_02.py 10 2.5
'''

import sys
import random

def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 3 :
        print ('usage: ', sys.argv[0], 'numero seed')
        exit ()

    random.seed (float (sys.argv[2]))
    randlist = []
    for i in range (int (sys.argv[1])):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (random.random ())
        print (i, randlist[-1])

    
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.3. Drawing of the obtained sequence of numbers#

  • random_03.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra 0 ed 1
a partire da un determinato seed e disegno della distribuzione
python3 random_03.py 200 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 3 :
        print ('usage: ', sys.argv[0], 'numero seed')
        exit ()

    random.seed (float (sys.argv[2]))
    randlist = []
    for i in range (int (sys.argv[1])):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (random.random ())
        print (i, randlist[-1])

    # plotting of the generated list of numbers in a histogram

    xMin = 0.                                    # minimum of the histogram drawing range
    xMax = 1.                                    # maximum of the histogram drawing range
    nBins = floor (len (randlist) / 20.) + 1     # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins)  # edges o the histogram bins

    # check the bin edges
    print (bin_edges)
    print (len (bin_edges))

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Histogram of random numbers', size=14)
    ax.set_xlabel('random value')
    ax.set_ylabel('events in bin')
    ax.hist (randlist,      # list of numbers
             bins = bin_edges,
             color = 'orange',
             # normed = True,
            )
    plt.show ()
    
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.4. Porting of the generation code to a library#

  • random_04.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra 0 ed 1
a partire da un determinato seed e disegno della distribuzione,
separando la generazione dal programma principale
python3 random_04.py 2000 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

from myrand import generate_uniform

def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 3 :
        print ('usage: ', sys.argv[0], 'numero seed')
        exit ()

    randlist = generate_uniform (int (sys.argv[1]), float (sys.argv[2]))

    # plotting of the generated list of numbers in a histogram

    xMin = 0.                                    # minimum of the histogram drawing range
    xMax = 1.                                    # maximum of the histogram drawing range
    nBins = floor (len (randlist) / 20.) + 1     # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins)  # edges o the histogram bins

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Histogram of random numbers', size=14)
    ax.set_xlabel('random value')
    ax.set_ylabel('events in bin')
    ax.hist (randlist,      # list of numbers
             bins = bin_edges,
             color = 'orange',
             # normed = True,
            )
    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()
  • myrand.py

#!/usr/bin/python

import random
from math import sqrt


def generate_uniform (N, seed = 0.) :
    '''
    generazione di N numeri pseudo-casuali distribuiti fra 0 ed 1
    a partire da un determinato seed
    '''
    if seed != 0. : random.seed (float (seed))
    randlist = []
    for i in range (N):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (random.random ())
    return randlist


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def rand_range (xMin, xMax) :
    '''
    generazione di un numero pseudo-casuale distribuito fra xMin ed xMax
    '''
    return xMin + random.random () * (xMax - xMin)


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def generate_range (xMin, xMax, N, seed = 0.) :
    '''
    generazione di N numeri pseudo-casuali distribuiti fra xMin ed xMax
    a partire da un determinato seed
    '''
    if seed != 0. : random.seed (float (seed))
    randlist = []
    for i in range (N):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (rand_range (xMin, xMax))
    return randlist


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def rand_TAC (f, xMin, xMax, yMax) :
    '''
    generazione di un numero pseudo-casuale 
    con il metodo try and catch
    '''
    x = rand_range (xMin, xMax)
    y = rand_range (0, yMax)
    while (y > f (x)) :
        x = rand_range (xMin, xMax)
        y = rand_range (0, yMax)
    return x


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def generate_TAC (f, xMin, xMax, yMax, N, seed = 0.) :
    '''
    generazione di N numeri pseudo-casuali
    con il metodo try and catch, in un certo intervallo,
    a partire da un determinato seed
    '''
    if seed != 0. : random.seed (float (seed))
    randlist = []
    for i in range (N):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (rand_TAC (f, xMin, xMax, yMax))
    return randlist


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def rand_TCL (xMin, xMax, N_sum = 10) :
    '''
    generazione di un numero pseudo-casuale 
    con il metodo del teorema centrale del limite
    su un intervallo fissato
    '''
    y = 0.
    for i in range (N_sum) :
        y = y + rand_range (xMin, xMax)
    y /= N_sum ;
    return y ;


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def generate_TCL (xMin, xMax, N, N_sum = 10, seed = 0.) :
    '''
    generazione di N numeri pseudo-casuali
    con il metodo del teorema centrale del limite, in un certo intervallo,
    a partire da un determinato seed
    '''
    if seed != 0. : random.seed (float (seed))
    randlist = []
    for i in range (N):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (rand_TCL (xMin, xMax, N_sum))
    return randlist


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def rand_TCL_ms (mean, sigma, N_sum = 10) :
    '''
    generazione di un numero pseudo-casuale 
    con il metodo del teorema centrale del limite
    note media e sigma della gaussiana
    '''
    y = 0.
    delta = sqrt (3 * N_sum) * sigma
    xMin = mean - delta
    xMax = mean + delta
    for i in range (N_sum) :
        y = y + rand_range (xMin, xMax)
    y /= N_sum ;
    return y ;


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def generate_TCL_ms (mean, sigma, N, N_sum = 10, seed = 0.) :
    '''
    generazione di N numeri pseudo-casuali
    con il metodo del teorema centrale del limite, note media e sigma della gaussiana,
    a partire da un determinato seed
    '''
    if seed != 0. : random.seed (float (seed))
    randlist = []
    delta = sqrt (3 * N_sum) * sigma
    xMin = mean - delta
    xMax = mean + delta
    for i in range (N):
        # Return the next random floating point number in the range 0.0 <= X < 1.0
        randlist.append (rand_TCL (xMin, xMax, N_sum))
    return randlist


4.6.5. Generation of pseudo-random numbers uniformly within (xMin, xMax)#

  • random_05.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra xMin ed xMax
a partire da un determinato seed e disegno della distribuzione,
separando la generazione dal programma principale
python3 random_05.py 2.2 4.3 2000 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

from myrand import generate_range

def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 5 :
        print ('usage: ', sys.argv[0], 'xMin xMax numero seed')
        exit ()

    xMin = float (sys.argv[1])  # minimum of the histogram drawing range
    xMax = float (sys.argv[2])  # maximum of the histogram drawing range
    seed = float (sys.argv[4])
    N    = int (sys.argv[3])

    print (' -------- ')
    print (' minimum : ', xMin)
    print (' maximum : ', xMax)
    print (' seed    : ', seed)
    print (' N       : ', N)
    print (' -------- ')

    randlist = generate_range (xMin, xMax, N, seed)

    # plotting of the generated list of numbers in a histogram

    nBins = floor (len (randlist) / 20.) + 1     # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins)  # edges o the histogram bins

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Histogram of random numbers', size=14)
    ax.set_xlabel ('random value')
    ax.set_ylabel ('events in bin')
    ax.hist (randlist,      # list of numbers
             bins = bin_edges,
             color = 'orange',
             # normed = True,
            )
    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.6. Visualisation of a pseudo-random sequence#

  • random_06.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra xMin ed xMax
a partire da un determinato seed e disegno della sequenza di numeri,
separando la generazione dal programma principale
python3 random_06.py 2.2 4.3 20 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

from myrand import generate_range

def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 5 :
        print ('usage: ', sys.argv[0], 'xMin xMax numero seed')
        exit ()

    xMin = float (sys.argv[1])  # minimum of the histogram drawing range
    xMax = float (sys.argv[2])  # maximum of the histogram drawing range
    seed = float (sys.argv[4])
    N    = int (sys.argv[3])

    print (' -------- ')
    print (' minimum : ', xMin)
    print (' maximum : ', xMax)
    print (' seed    : ', seed)
    print (' N       : ', N)
    print (' -------- ')

    # list of uniformly generated numbers
    randlist = generate_range (xMin, xMax, N, seed)
    # list of the position indices of the pseudo-random numbers in randlist
    index = range (len (randlist))

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Sequence of random numbers', size=14)
    ax.set_xlabel ('index in the sequence')
    ax.set_ylabel ('random value')
#    ax.scatter (index, randlist)
    ax.plot (index, randlist, marker = 'o')
    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.7. Visualisation of a pseudo-random sequence and its distribution#

  • random_07.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti uniformemente fra xMin ed xMax
a partire da un determinato seed e disegno congiunto della loro distribuzione e sequenza,
separando la generazione dal programma principale
reference documentation:
https://matplotlib.org/stable/gallery/axes_grid1/scatter_hist_locatable_axes.html#sphx-glr-gallery-axes-grid1-scatter-hist-locatable-axes-py
python3 random_07.py 2.2 4.3 100 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from math import floor

from myrand import generate_range


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 5 :
        print ('usage: ', sys.argv[0], 'xMin xMax numero seed')
        exit ()

    xMin = float (sys.argv[1])  # minimum of the histogram drawing range
    xMax = float (sys.argv[2])  # maximum of the histogram drawing range
    seed = float (sys.argv[4])
    N    = int (sys.argv[3])

    print (' -------- ')
    print (' minimum : ', xMin)
    print (' maximum : ', xMax)
    print (' seed    : ', seed)
    print (' N       : ', N)
    print (' -------- ')

    # list of uniformly generated numbers
    randlist = generate_range (xMin, xMax, N, seed)
    # list of the position indices of the pseudo-random numbers in randlist
    index = range (len (randlist))

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Sequence of random numbers', size=14)
    ax.set_xlabel ('index in the sequence')
    ax.set_ylabel ('random value')
#    ax.scatter (index, randlist)
    ax.plot (index, randlist, marker = 'o')

    # create a new axis on the left of the current axes
    divider = make_axes_locatable (ax)
    # below height and pad are in inches
    ax_histy = divider.append_axes ("right", 1.2, pad=0.1, sharey=ax)
    ax_histy.set_xlabel ('counts')

    # make some labels invisible
    ax_histy.yaxis.set_tick_params (labelleft=False)

    nBins = floor (len (randlist) / 10.) + 1     # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins)  # edges o the histogram bins

    ax_histy.hist (randlist,      # list of numbers
                   bins = bin_edges,
                   color = 'orange',
                   orientation='horizontal',
                   # normed = True,
                  )
    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.8. Generation of pseudo-random numbers with the try-and-catch method#

  • random_08.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti secondo una distribuzione arbitraria
con il metodo try-and-catch fra xMin ed xMax
a partire da un determinato seed e disegno della distribuzione,
separando la generazione dal programma principale
python3 random_08.py 0. 10 2. 20000 2.4
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

from myrand import generate_TAC


def func (x, scale = 1) : 
    '''
    funzione definita positiva sotto la quale generare numeri casuali
    '''
    return scale * (np.cos (x) + 1.)


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 6 :
        print ('usage: ', sys.argv[0], 'xMin xMax numero seed')
        exit ()

    xMin = float (sys.argv[1])  # minimum of the histogram drawing range
    xMax = float (sys.argv[2])  # maximum of the histogram drawing range
    yMax = float (sys.argv[3])  # maximum of the histogram drawing range    
    seed = float (sys.argv[5])
    N    = int (sys.argv[4])

    print (' -------- ')
    print (' minimum : ', xMin)
    print (' maximum : ', xMax)
    print (' seed    : ', seed)
    print (' N       : ', N)
    print (' -------- ')

    randlist = generate_TAC (func, xMin, xMax, yMax, N, seed)

    # plotting of the generated list of numbers in a histogram

    nBins = floor (len (randlist) / 400.)             # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins + 1)  # edges o the histogram bins

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Histogram of random numbers', size=14)
    ax.set_xlabel ('random value')
    ax.set_ylabel ('events in bin')
    ax.hist (randlist,      # list of numbers
             bins = bin_edges,
             color = 'orange',
             # normed = True,
            )

    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()

4.6.9. Generation of pseudo-random numbers with the central limit theorem method#

  • random_09.py

#!/usr/bin/python
'''
generazione di numeri pseudo-casuali distribuiti secondo una distribuzione Gaussiana
con il metodo del teorema centrale del limite fra xMin ed xMax
a partire da un determinato seed e disegno della distribuzione,
separando la generazione dal programma principale
python3 random_09.py 0. 10 20000 2.4 10
'''

import sys
import random
import matplotlib.pyplot as plt
import numpy as np
from math import floor

from myrand import generate_TCL


def main () :
    '''
    Funzione che implementa il programma principale
    '''

    if len(sys.argv) < 6:
        print ('usage: ', sys.argv[0], 'xMin xMax numero seed')
        exit ()

    xMin  = float (sys.argv[1])  # minimum of the histogram drawing range
    xMax  = float (sys.argv[2])  # maximum of the histogram drawing range
    seed  = float (sys.argv[4])
    N     = int (sys.argv[3])
    N_sum = int (sys.argv[5])

    print (' -------- ')
    print (' minimum : ', xMin)
    print (' maximum : ', xMax)
    print (' seed    : ', seed)
    print (' N       : ', N)
    print (' N_sum   : ', N_sum)
    print (' -------- ')

    randlist = generate_TCL (xMin, xMax, N, N_sum, seed)

    # plotting of the generated list of numbers in a histogram

    nBins = floor (len (randlist) / 400.)             # number of bins of the hitogram
    bin_edges = np.linspace (xMin, xMax, nBins + 1)  # edges o the histogram bins

    # disegno della funzione
    fig, ax = plt.subplots ()
    ax.set_title ('Histogram of random numbers', size=14)
    ax.set_xlabel ('random value')
    ax.set_ylabel ('events in bin')
    ax.hist (randlist,      # list of numbers
             bins = bin_edges,
             color = 'orange',
             # normed = True,
            )

    plt.show ()


# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 


if __name__ == "__main__":
    main ()