Sha256: d51305c7f2015a66959df4fc6f94df9589d038867ad1cbae890a971e944bf389

Contents?: true

Size: 627 Bytes

Versions: 9

Compression:

Stored size: 627 Bytes

Contents

require 'facets/math/sum'
require 'facets/math/mean'
require 'facets/math/approx_equal'

module Math

  # Calculates the Theil index (a statistic used to measure
  # economic inequality).
  #
  # TI = \sum_{i=1}^N \frac{x_i}{\sum_{j=1}^N x_j} ln \frac{x_i}{\bar{x}}
  #
  #   http://en.wikipedia.org/wiki/Theil_index
  #
  def self.theil_index(array)
    return -1 if array.size <= 0 or any? { |x| x < 0 }
    return  0 if array.size <  2 or all? { |x| approx_equal(x, 0) }
    m = mean(array)
    s = sum(array).to_f
    inject(0) do |theil, xi|
	    theil + ((xi > 0) ? (log(xi.to_f/m) * xi.to_f/s) : 0.0)
    end
  end

end

Version data entries

9 entries across 8 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/standard/facets/math/theil_index.rb
facets-3.1.0 lib/standard/facets/math/theil_index.rb
facets-3.0.0 lib/standard/facets/math/theil_index.rb
facets-2.9.3 lib/standard/facets/math/theil_index.rb
facets-2.9.2 src/standard/facets/math/theil_index.rb
facets-2.9.2 lib/standard/facets/math/theil_index.rb
facets-2.9.1 lib/standard/facets/math/theil_index.rb
facets-2.9.0 lib/more/facets/math/theil_index.rb
facets-2.9.0.pre.2 lib/more/facets/math/theil_index.rb