Class: MoreMath::Histogram

Inherits:
Object show all
Defined in:
lib/more_math/histogram.rb

Overview

A histogram gives an overview of a sequence’s elements.

Defined Under Namespace

Classes: Bin

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sequence, bins = 10) ⇒ Histogram

Create a Histogram for the elements of sequence with bins bins.



7
8
9
10
11
# File 'lib/more_math/histogram.rb', line 7

def initialize(sequence, bins = 10)
  @sequence = sequence
  @bins = bins
  @result = compute
end

Instance Attribute Details

#binsObject (readonly)

Number of bins for this Histogram.



14
15
16
# File 'lib/more_math/histogram.rb', line 14

def bins
  @bins
end

Instance Method Details

#countsObject



25
26
27
# File 'lib/more_math/histogram.rb', line 25

def counts
  each_bin.map(&:count)
end

#display(output = $stdout, width = 50) ⇒ Object

Display this histogram to output, width is the parameter for prepare_display



31
32
33
34
35
36
37
38
# File 'lib/more_math/histogram.rb', line 31

def display(output = $stdout, width = 50)
  d = prepare_display(width)
  for l, bar, r in d
    output << "%11.5f -|%s\n" % [ (l + r) / 2.0, "*" * bar ]
  end
  output << "max_count=#{max_count}\n"
  self
end

#each_bin(&block) ⇒ Object



21
22
23
# File 'lib/more_math/histogram.rb', line 21

def each_bin(&block)
  @result.each(&block)
end

#max_countObject



40
41
42
# File 'lib/more_math/histogram.rb', line 40

def max_count
  counts.max
end

#to_aObject

Return the computed histogram as an array of Bin objects.



17
18
19
# File 'lib/more_math/histogram.rb', line 17

def to_a
  @result
end