Module: Rust::Descriptive

Defined in:
lib/rust-descriptive.rb

Class Method Summary collapse

Class Method Details

.mean(data) ⇒ Object

Raises:

  • (TypeError)


7
8
9
10
11
# File 'lib/rust-descriptive.rb', line 7

def mean(data)
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    
    return data.sum.to_f / data.size
end

.median(data) ⇒ Object

Raises:

  • (TypeError)


30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rust-descriptive.rb', line 30

def median(data)
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    
    sorted = data.sort
    if data.size == 0
        return Float::NAN
    elsif data.size.odd?
        return sorted[data.size / 2]
    else
        i = (data.size / 2)
        return (sorted[i - 1] + sorted[i]) / 2.0
    end
end

.quantile(data, percentiles = [0.0, 0.25, 0.5, 0.75, 1.0]) ⇒ Object

Raises:

  • (TypeError)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rust-descriptive.rb', line 50

def quantile(data, percentiles=[0.0, 0.25, 0.5, 0.75, 1.0])
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    raise TypeError, "Expecting Array of numerics" if !percentiles.is_a?(Array) || !percentiles.all? { |e| e.is_a?(Numeric) }
    raise "Percentiles outside the range: #{percentiles}" if percentiles.any? { |e| !e.between?(0, 1) } 
    
    Rust.exclusive do 
        Rust['descriptive.data'] = data
        Rust['descriptive.percs'] = percentiles
        
        call_result = Rust._pull("quantile(descriptive.data, descriptive.percs)")
        assert { call_result.is_a?(Array) }
        assert { call_result.size == percentiles.size }
        
        return percentiles.zip(call_result).to_h
    end
end

.standard_deviation(data) ⇒ Object Also known as: sd, stddev

Raises:

  • (TypeError)


13
14
15
16
17
# File 'lib/rust-descriptive.rb', line 13

def standard_deviation(data)
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    
    return Math.sqrt(variance(data))
end

.sum(data) ⇒ Object

Raises:

  • (TypeError)


44
45
46
47
48
# File 'lib/rust-descriptive.rb', line 44

def sum(data)
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    
    return data.sum
end

.variance(data) ⇒ Object Also known as: var

Raises:

  • (TypeError)


21
22
23
24
25
26
27
# File 'lib/rust-descriptive.rb', line 21

def variance(data)
    raise TypeError, "Expecting Array of numerics" if !data.is_a?(Array) || !data.all? { |e| e.is_a?(Numeric) }
    return Float::NAN if data.size < 2
    
    mean = mean(data)
    return data.map { |v| (v - mean) ** 2 }.sum.to_f / (data.size - 1)
end