Sha256: 8ef19111b1eed4b93bafbdd55ceeac9d1c467b6e28bd9988a430e52d28ce8953

Contents?: true

Size: 975 Bytes

Versions: 22

Compression:

Stored size: 975 Bytes

Contents

#--
# Credit goes to Derek.
#++
require 'facet/enumerable/ideal_entropy'
require 'facet/enumerable/probability'

module Enumerable
  # Shannon's entropy for an array - returns the average
  # bits per symbol required to encode the array.
  # Lower values mean less "entropy" - i.e. less unique
  # information in the array.
  #
  #   %w{ a b c d e e e }.entropy  #=>
  #
  def entropy
    arr = self.to_a
    probHash = arr.probability
    # h is the Shannon entropy of the array
    h = -1.to_f * probHash.keys.inject(0.to_f) do |sum, i|
      sum + (probHash[i] * (Math.log(probHash[i])/Math.log(2.to_f)))
    end
    h
  end
end

class String
  def entropy
    self.split(//).entropy
  end
end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_entropy
      assert_equal( 1.0, %w{ a b }.entropy )
    end

  end

=end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/enumerable/entropy.rb
facets-1.0.3 packages/core/lib/facet/enumerable/entropy.rb
facets-1.3.0 lib/facets/core/enumerable/entropy.rb
facets-1.1.0 lib/facet/enumerable/entropy.rb
facets-1.2.0 lib/facets/core/enumerable/entropy.rb
facets-1.2.1 lib/facets/core/enumerable/entropy.rb
facets-1.3.1 lib/facets/core/enumerable/entropy.rb
facets-1.3.3 lib/facets/core/enumerable/entropy.rb
facets-1.3.2 lib/facets/core/enumerable/entropy.rb
facets-1.4.1 lib/facets/core/enumerable/entropy.rb
facets-1.4.2 lib/facets/core/enumerable/entropy.rb
facets-1.4.0 lib/facets/core/enumerable/entropy.rb
facets-1.4.3 lib/facets/core/enumerable/entropy.rb
facets-1.4.4 lib/facets/core/enumerable/entropy.rb
facets-1.4.5 lib/facets/core/enumerable/entropy.rb
facets-1.7.38 lib/facets/core/enumerable/entropy.rb
facets-1.7.0 lib/facets/core/enumerable/entropy.rb
facets-1.7.30 lib/facets/core/enumerable/entropy.rb
facets-1.7.46 lib/facets/core/enumerable/entropy.rb
facets-1.8.0 lib/facets/core/enumerable/entropy.rb