class Binomial

Public Class Methods

new(n: nil, p: nil, tries: nil, probability: nil, failure: nil) click to toggle source
@param n [Fixnum] number of tries
@param p [Float] probability of success
@param tries [Fixnum] alias for n
@param probability [Float] alias for p

 @param failure [Float] alias for `p = 1 - failure`

@note if no probability is defined, the default value will be 0.5
# File lib/binomial_distribution.rb, line 38
def initialize n: nil, p: nil, tries: nil, probability: nil, failure: nil
  tries_count = n || tries
  probability = p || probability || (failure && 1.0 - failure) || 0.5
  raise ArgumentError, "The argument `n` `#{tries_count}` is not an Integer" unless tries_count.is_a? Integer
  raise ArgumentError, "The argument `p` `#{probability}` is not a Numeric" unless probability.is_a? Numeric
  tries_count = Float(tries_count)
  raise Math::DomainError, "The argument `n` `#{tries_count}` is not in greater or equal to 0" if tries_count < 0.0
  raise Math::DomainError, "The argument `p` `#{probability}` is not in greater or equal to 0" if probability < 0.0
  raise Math::DomainError, "The argument `p` `#{probability}` is not in lesser or equal to 1" if probability > 1.0
  @n = tries_count.to_i
  @p = probability.to_f
end

Public Instance Methods

distribute(k) click to toggle source

@param k [Fixnum] number of test successful. @param k [Enumerable] list of number of test successful. @return [Float] probability

# File lib/binomial_distribution.rb, line 58
def distribute k
  if k.is_a? Enumerable
    distribute_enumerable k
  elsif k.is_a? Integer
    distribute_integer k
  else
    raise ArgumentError
  end
end
to_s() click to toggle source
# File lib/binomial_distribution.rb, line 51
def to_s
  "#<#{self.class} @n=#@n, @p=#@p>"
end

Private Instance Methods

distribute_enumerable(k) click to toggle source
# File lib/binomial_distribution.rb, line 68
        def distribute_enumerable k
  k.map{|p| distribute_integer(p) }.reduce(&:+)
end
distribute_integer(k) click to toggle source
# File lib/binomial_distribution.rb, line 72
        def distribute_integer k
  raise Math::SuperiorityError, "the number of success must be lesser or equal to the number of tries (#{@n})" if k > @n
  Math.coef_binomial(@n, k) * @p**k * (1 - @p) ** (@n - k)
end