Sha256: 39b4d3176c0794e2cb69125f94d43954980801414577784fc5998d53caf974a1

Contents?: true

Size: 638 Bytes

Versions: 12

Compression:

Stored size: 638 Bytes

Contents

module MoreMath
  module Entropy
    def entropy(text)
      chars = text.chars
      size  = chars.size

      chars.each_with_object(Hash.new(0.0)) { |c, h| h[c] += 1 }.
        each_value.reduce(0.0) do |entropy, count|
          frequency = count / size
          entropy + frequency * Math.log2(frequency)
        end.abs
    end

    def entropy_ideal(size)
      size <= 1 and return 0.0
      frequency = 1.0 / size
      -1.0 * size * frequency * Math.log2(frequency)
    end

    def entropy_ratio(text)
      size = text.each_char.size
      size <= 1 and return 0.0
      entropy(text) / entropy_ideal(size)
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
more_math-1.3.0 lib/more_math/entropy.rb
more_math-1.2.2 lib/more_math/entropy.rb
more_math-1.2.1 lib/more_math/entropy.rb
more_math-1.2.0 lib/more_math/entropy.rb
more_math-1.1.0 lib/more_math/entropy.rb
more_math-1.0.2 lib/more_math/entropy.rb
more_math-1.0.1 lib/more_math/entropy.rb
more_math-1.0.0 lib/more_math/entropy.rb
more_math-0.4.0 lib/more_math/entropy.rb
more_math-0.3.3 lib/more_math/entropy.rb
more_math-0.3.2 lib/more_math/entropy.rb
more_math-0.3.1 lib/more_math/entropy.rb