Monte Carlo Simulation with Python: building a histogram on the fly
Here is a possible solution, with fixed bin size, and bins of the form [k * size, (k + 1) * size[. The function finalizebins returns two lists: one with bin counts (a), and the other (b) with bin lower bounds (the upper bound is deduced by adding binsize).
import math, randomdef updatebins(bins, binsize, x): i = math.floor(x / binsize) if i in bins: bins[i] += 1 else: bins[i] = 1def finalizebins(bins, binsize): imin = min(bins.keys()) imax = max(bins.keys()) a = [0] * (imax - imin + 1) b = [binsize * k for k in range(imin, imax + 1)] for i in range(imin, imax + 1): if i in bins: a[i - imin] = bins[i] return a, b# A test with a mixture of gaussian distributionsdef check(n): bins = {} binsize = 5.0 for i in range(n): if random.random() > 0.5: x = random.gauss(100, 50) else: x = random.gauss(-200, 150) updatebins(bins, binsize, x) return finalizebins(bins, binsize)a, b = check(10000)# This must be 10000sum(a)# Plot the datafrom matplotlib.pyplot import *bar(b,a)show()