Skip to content

Instantly share code, notes, and snippets.

@shoyan shoyan/entropy
Last active Jun 30, 2016

Embed
What would you like to do?
エントロピーを計算するツール
#!/usr/bin/env ruby
# Usage
# ./entropy file
# echo "aaaaaaaabbbbbbbbbcc" | ./entropy
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: entropy [options] file"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
def entropy(str, options)
count = str.size
list={}
list.default=0
str.split("").each {|c| list[c]+=1}
sum = 0
if options[:verbose]
puts "記号: 確率 : 値"
end
list.each do |key, val|
i = (val.to_f / count.to_f)
tmp_e = -(i) * Math.log(i, 2)
if options[:verbose]
puts "#{key}: #{val} / #{count}: #{tmp_e}"
end
sum += tmp_e
end
sum
end
if $stdin.tty?
file = ARGV[0]
str = File.read(file)
else
str = ARGF.read.chomp
end
e = entropy(str, options)
if options[:verbose]
puts ""
puts "サイズ エントロピー 下限値"
puts "#{str.bytesize} #{e} #{((str.bytesize * e) / 8).to_i}"
else
puts e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.