Class: Hetchy::Dataset

Inherits:
Object
  • Object
show all
Defined in:
lib/hetchy/dataset.rb

Overview

Takes a fixed immutable dataset (array of values) and provides various statistical measurements.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Dataset

Returns a new instance of Dataset.



11
12
13
14
# File 'lib/hetchy/dataset.rb', line 11

def initialize(data)
  @data = data.sort
  @size = @data.length
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



8
9
10
# File 'lib/hetchy/dataset.rb', line 8

def data
  @data
end

#sizeObject (readonly)

Returns the value of attribute size.



8
9
10
# File 'lib/hetchy/dataset.rb', line 8

def size
  @size
end

Instance Method Details

#medianFloat/Integer

Returns median of the data set.

Returns:

  • (Float/Integer)

    median of the data set.



17
18
19
# File 'lib/hetchy/dataset.rb', line 17

def median
  percentile(50.0)
end

#percentile(perc) ⇒ Object

Generate a percentile for the data set.

Examples:

snapshot.percentile(95)
snapshot.percentile(99.9)


26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hetchy/dataset.rb', line 26

def percentile(perc)
  if perc > 100.0 || perc < 0.0
    raise InvalidPercentile, "percentile must be between 0.0 and 100.0"
  end
  return 0.0 if data.empty?

  rank = (perc / 100.0) * (size + 1)

  return data[0]          if rank < 1
  return data[-1]         if rank > size
  return data[rank - 1]   if rank == Integer(rank)
  weighted_average_for(rank)
end