Last active
June 30, 2016 02:03
-
-
Save shoyan/cfa5528ccd9388eee25b2e120c4c452b to your computer and use it in GitHub Desktop.
エントロピーを計算するツール
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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