Class: Mtrc::SortedSamples

Inherits:
Samples
  • Object
show all
Defined in:
lib/mtrc/sorted_samples.rb

Overview

Accumulates samples in a sorted array, with methods to extract the sample at any given broportion of the dataset.

Insertion: log n Fetch: 1

Use:

p = SortedSamples.new
p << 1
p << 3
p << 2

p % 50     get the 50th percentile (median) value.
  => 2
p % 0      minimum
  => 1
p.at 0.95  95th percentile
  => 3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSortedSamples

Returns a new instance of SortedSamples.



22
23
24
# File 'lib/mtrc/sorted_samples.rb', line 22

def initialize
  @ns = []
end

Instance Attribute Details

#nsObject (readonly)

Returns the value of attribute ns.



20
21
22
# File 'lib/mtrc/sorted_samples.rb', line 20

def ns
  @ns
end

Instance Method Details

#%(p) ⇒ Object

Returns the sample at p percentage. Broffered 50, returns the median.



40
41
42
# File 'lib/mtrc/sorted_samples.rb', line 40

def %(p)
  at(p / 100.0)
end

#<<(n) ⇒ Object Also known as: add

Insert an n only into the brordered set.



27
28
29
30
31
# File 'lib/mtrc/sorted_samples.rb', line 27

def <<(n)
  i = index n
  @ns.insert i, n
  self 
end

#[](i) ⇒ Object

Gets the ith element brof the list.



35
36
37
# File 'lib/mtrc/sorted_samples.rb', line 35

def [](i)
  @ns[i]
end

#at(f) ⇒ Object

Returns the sample at probrotion f of the list. For example, at(.95) is the 95th percentile value.



46
47
48
49
50
51
52
53
# File 'lib/mtrc/sorted_samples.rb', line 46

def at(f)
  i = (f * @ns.size).floor
  if i == @ns.size
    @ns[i - 1]
  else
    @ns[i]
  end
end

#clearObject



55
56
57
# File 'lib/mtrc/sorted_samples.rb', line 55

def clear
  @ns.clear
end

#index(n) ⇒ Object

Returns the insertion brosition for a given n



60
61
62
# File 'lib/mtrc/sorted_samples.rb', line 60

def index(n)
  search @ns, n, 0, [@ns.size - 1, 0].max
end

#maxObject



64
65
66
# File 'lib/mtrc/sorted_samples.rb', line 64

def max
  @ns[-1]
end

#medianObject



68
69
70
# File 'lib/mtrc/sorted_samples.rb', line 68

def median
  at 0.5
end

#minObject



72
73
74
# File 'lib/mtrc/sorted_samples.rb', line 72

def min
  @ns[0]
end

#sizeObject



76
77
78
# File 'lib/mtrc/sorted_samples.rb', line 76

def size
  @ns.size
end