# simpleMC.py -- simple Monte Carlo program to make histogram of uniformly
# distributed random values and plot
# G. Cowan, RHUL Physics, October 2025

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Generate data and store in numpy array, put into histogram
numVal = 10000
nBins = 100
xMin = 0.
xMax = 1.
xData = np.random.uniform(xMin, xMax, numVal)
xHist, bin_edges = np.histogram(xData, bins=nBins, range=(xMin,xMax))

# Define a function for plotting histograms
def plot_histogram(hist, bin_edges, xlabel, ylabel, filename=None):
    xMin = bin_edges[0]
    xMax = bin_edges[-1]
    x_step = bin_edges                          
    y_step = np.r_[hist, hist[-1]]              # r_ does row-wise merge
    fig, ax = plt.subplots()
    ax.step(x_step, y_step, where='post', linewidth=1.5)
    ax.set_xlim(xMin, xMax)
    ax.set_ylim(0, 1.2 * hist.max())
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    fig.subplots_adjust(bottom=0.15, left=0.15)
    if filename != None:
        fig.savefig(filename, format='pdf')        
    plt.show()

plot_histogram(xHist, bin_edges, r'$x$', 'counts')

