Skip to content

Instantly share code, notes, and snippets.

@ymurase
Created May 2, 2014 05:56
Show Gist options
  • Save ymurase/d3ec0ba9a596210bf16a to your computer and use it in GitHub Desktop.
Save ymurase/d3ec0ba9a596210bf16a to your computer and use it in GitHub Desktop.
take histogram with normal-binning and log-binning
require 'pp'
class Histogram
def self.normal_histo(data)
histo = Hash.new(0)
data.each do |d|
histo[d] += 1
end
histo.sort_by {|a| a[0]}
end
def self.logbin_histo(data)
histo = Hash.new(0)
data.each do |d|
key = 2 ** (Math.log(d.to_f)/Math.log(2.0)).to_i
histo[key] += 1
end
histo.map {|key,val| [key, val.to_f/key] }.sort_by {|a| a[0]}
end
def self.histo_to_s(histo)
histo.map {|a| a.join(' ')}.join("\n")
end
end
if $0 == __FILE__
data = [1,1,1,2,2,3,3,3,4,5,8]
pp Histogram.normal_histo(data) # => [ [1,3], [2,2], [3,3], [4,1], [5,1], [8,1] ]
pp Histogram.logbin_histo(data) # => [ [1,3], [2,2.5], [4,0.5], [8,0.125] ]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment