Skip to content
Extraits de code Groupes Projets
histogram.py 1,95 ko
Newer Older
  • Learn to ignore specific revisions
  • Martin Delcourt's avatar
    Martin Delcourt a validé
    
    
    class Histogram:
        def __init__(self, n_bins = 0, a = 0, b = 0):
            """Crée un histograme de n_bins réparties uniformément entre a et b"""
            self._data = [0 for i in range(n_bins)]
            self._n_bins = n_bins
            self._a = a
            self._b = b
    
        def fill(self, x):
            """Remplis la bin correspondant à la valeur 'x'"""
            bin_number = int((x-self._a)*self._n_bins/(self._b-self._a))
            if bin_number >= 0 and bin_number < self._n_bins:
                self._data[bin_number] += 1
                return bin_number
            else:
                print("Warning, {} out of bounds.".format(x))
                return -1
    
        def get_maximum(self):
            """Retourne le maximum de l'histogramme"""
            maximum = self._data[0]
            for x in self._data[1:]:
                if x > maximum:
                    maximum = x
            return maximum
    
    
        def draw(self):
            """Affiche l'histogramme en console"""
            y_max = self.get_maximum()
            scale = 1.
            if y_max > 50:
                scale = 50*1./y_max
                y_max = 50
            # vertical axis : 50 pxl
            y = y_max + 1
            while y > 0:
                to_print = ""
                if (y == y_max+1):
                    to_print = "y ^"
                else:
                    to_print = "  |"
    
                for x in range(self._n_bins):
                    if self._data[x] >= y/scale:
                        to_print += "#"
                    else:
                        to_print += " "
                print (to_print)
                y-=1
    
            print (" -"+"+"+(self._n_bins-1)*"-"+">")
            print ("  |"+(self._n_bins-1)*" "+"x")
            if scale != 1:
                print ("y-axis scale : 1 # = {}".format(1./scale))
    
    
    
    
    if __name__=="__main__":
        h = Histogram(10,0,1)
        h.fill(0.5)
        h.fill(0.5)
        h.fill(0.5)
        h.fill(0.1)
        h.fill(2)
        h.fill(-1)
        h.draw()
    
        h2 = Histogram(100,-5,5)
        from random import gauss
        for i in range(int(100000)):
            h2.fill(gauss(0,1))
        h2.draw()