code: def knuth(data):
          
          import scipy.optimize as optimize
  
          def f(data):
              from scipy.special import gammaln
  
              m, M = np.min(data), np.max(data)
              n = len(data)
  
              def fff(x):
                  k = x[0]  # number of bins
                  if k <= 0:
                      return float("+inf")
                  binning = np.linspace(m, M, k + 1)
                  histo, bincenters = np.histogram(data, binning)
  
                  return -(n * np.log(k) + gammaln(k / 2.) - gammaln(n + k / 2.) +
                           k * gammaln(1. / 2.) + np.sum(gammaln(histo + 0.5)))
              return fff
  
          k0 = np.sqrt(len(data))
          return optimize.fmin(f(data), np.array([k0]), disp=False)[0]
docs: References
          ----------
          .. [1] K. Knuth, "Optimal Data-Based Binning for Histograms", 2006.
                 http://arxiv.org/pdf/physics/0605197v1.pdf