File: binomial.rb

package info (click to toggle)
ruby-statistics 2.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 224 kB
  • sloc: ruby: 989; sh: 4; makefile: 4
file content (49 lines) | stat: -rw-r--r-- 1,313 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
module Statistics
  module Distribution
    class Binomial
      attr_accessor :number_of_trials, :probability_per_trial
      def initialize(n, p)
        self.number_of_trials = n.to_i
        self.probability_per_trial = p
      end

      def probability_mass_function(k)
        return if k < 0 || k > number_of_trials
        k = k.to_i

        Math.combination(number_of_trials, k) *
          (probability_per_trial ** k) * ((1 - probability_per_trial) ** (number_of_trials - k))
      end

      def cumulative_function(k)
        return if k < 0 || k > number_of_trials
        k = k.to_i

        p = 1 - probability_per_trial
        Math.incomplete_beta_function(p, number_of_trials - k, 1 + k)
      end

      def mean
        number_of_trials * probability_per_trial
      end

      def variance
        mean * (1 - probability_per_trial)
      end

      def mode
        test = (number_of_trials + 1) * probability_per_trial

        returned = if test == 0 || (test % 1 != 0)
                     test.floor
                   elsif (test % 1 == 0)  && (test >= 1 && test <= number_of_trials)
                     [test, test - 1]
                   elsif test == number_of_trials + 1
                     number_of_trials
                   end

        returned
      end
    end
  end
end