Module: WilsonScore

Defined in:
lib/wilson_score.rb,
lib/wilson_score/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.interval(k, n, *args) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/wilson_score.rb', line 6

def self.interval(k, n, *args)
  args = args.dup
  options = args[-1].is_a?(Hash) ? args.pop : {}
  confidence = args[0] || options[:confidence] || 0.95
  correction = !args[1].nil? ? args[1] : (options.has_key?(:correction) ? options[:correction] : true)

  z = pnorm(1 - (1 - confidence) / 2.0)
  phat = k / n.to_f
  z2 = z**2
  if correction # continuity correction
    a = 2 * (n + z2)
    b = 2*n*phat + z2
    c = z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) + (4*phat - 2)) + 1
    d = z * Math.sqrt(z2 - 1.0/n + 4*n*phat*(1 - phat) - (4*phat - 2)) + 1
    lower = phat == 0 ? 0 : [0, (b - c) / a].max
    upper = phat == 1 ? 1 : [1, (b + d) / a].min
    lower..upper
  else
    a = 1 + z2 / n
    b = phat + z2 / (2 * n)
    c = z * Math.sqrt((phat * (1 - phat) + z2 / (4 * n)) / n)
    ((b - c) / a)..((b + c) / a)
  end
end

.lower_bound(k, n, options = {}) ⇒ Object



31
32
33
# File 'lib/wilson_score.rb', line 31

def self.lower_bound(k, n, options = {})
  interval(k, n, options).first
end

.rating_interval(avg, n, score_range, *args) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wilson_score.rb', line 35

def self.rating_interval(avg, n, score_range, *args)
  args = args.dup
  options = args[-1].is_a?(Hash) ? args.pop : {}
  confidence = args[0] || options[:confidence] || 0.95
  correction = !args[1].nil? ? args[1] : (options.has_key?(:correction) ? options[:correction] : true)

  min = score_range.first
  max = score_range.last
  range = max - min
  interval = interval(n * (avg - min) / range, n, confidence, correction)
  (min + range * interval.first)..(min + range * interval.last)
end

.rating_lower_bound(avg, n, score_range, options = {}) ⇒ Object



48
49
50
# File 'lib/wilson_score.rb', line 48

def self.rating_lower_bound(avg, n, score_range, options = {})
  rating_interval(avg, n, score_range, options).first
end