title: calculating Gini coefficient in Python/numpy
body: <p>i'm calculating <a href="https://en.wikipedia.org/wiki/Gini_coefficient" rel="noreferrer">Gini coefficient</a> (similar to: <a href="https://stackoverflow.com/questions/31416664/python-gini-coefficient-calculation-using-numpy">Python - Gini coefficient calculation using Numpy</a>) but i get an odd result. for a uniform distribution sampled from <code>np.random.rand()</code>, the Gini coefficient is 0.3 but I would have expected it to be close to 0 (perfect equality). what is going wrong here?</p>
  
  <pre><code>def G(v):
      bins = np.linspace(0., 100., 11)
      total = float(np.sum(v))
      yvals = []
      for b in bins:
          bin_vals = v[v &lt;= np.percentile(v, b)]
          bin_fraction = (np.sum(bin_vals) / total) * 100.0
          yvals.append(bin_fraction)
      # perfect equality area
      pe_area = np.trapz(bins, x=bins)
      # lorenz area
      lorenz_area = np.trapz(yvals, x=bins)
      gini_val = (pe_area - lorenz_area) / float(pe_area)
      return bins, yvals, gini_val
  
  v = np.random.rand(500)
  bins, result, gini_val = G(v)
  plt.figure()
  plt.subplot(2, 1, 1)
  plt.plot(bins, result, label="observed")
  plt.plot(bins, bins, '--', label="perfect eq.")
  plt.xlabel("fraction of population")
  plt.ylabel("fraction of wealth")
  plt.title("GINI: %.4f" %(gini_val))
  plt.legend()
  plt.subplot(2, 1, 2)
  plt.hist(v, bins=20)
  </code></pre>
  
  <p>for the given set of numbers, the above code calculates the fraction of the total distribution's values that are in each percentile bin.</p>
  
  <p>the result:</p>
  
  <p><a href="https://i.stack.imgur.com/YKOUG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YKOUG.png" alt="enter image description here"></a></p>
  
  <p>uniform distributions should be near "perfect equality" so the lorenz curve bending is off.</p>