Class: Bernoulli::Distribution::Binomial

Inherits:
Object
  • Object
show all
Includes:
Bernoulli::Distribution
Defined in:
lib/bernoulli/distribution/binomial.rb

Overview

Implements binomially distributed random variable See en.wikipedia.org/wiki/Binomial_distribution for more information

Instance Method Summary collapse

Methods included from Bernoulli::Distribution

#[], #probability_range, #standard_deviation

Constructor Details

#initialize(n, p) ⇒ Binomial

Returns a new instance of Binomial.

Parameters:

  • n (Integer)

    the number of trials (>= 0)

  • p (Float)

    success probability in each trial



16
17
18
19
20
21
22
# File 'lib/bernoulli/distribution/binomial.rb', line 16

def initialize(n, p)
  if n < 0 or p > 1.0 or p < 0.0
    raise 'Expecting n >= 0 and 0.0 <= p <= 1.0'
  end
  @n = n.to_i
  @p = p.to_f
end

Instance Method Details

#excessObject



64
65
66
# File 'lib/bernoulli/distribution/binomial.rb', line 64

def excess
  (1 - 6 * @p * (1 - @p)) / (@n * @p * (1 - @p))
end

#expected_valueObject Also known as: ev



50
51
52
# File 'lib/bernoulli/distribution/binomial.rb', line 50

def expected_value
  @n * @p
end

#probability(k) ⇒ Float

Returns the probability of ‘k` successes.

Parameters:

  • k (Integer)

    the number of successes (>= 0)

Returns:

  • (Float)

    the probability of ‘k` successes



30
31
32
# File 'lib/bernoulli/distribution/binomial.rb', line 30

def probability(k)
  Math.binomial(@n, k) * @p**k * (1 - @p)**(@n - k)
end

#sampleArray<0, 1>

Preform a binomial experiment of length ‘@n` and probability `@p`

Returns:

  • (Array<0, 1>)

    the resulting random array



36
37
38
39
40
41
42
# File 'lib/bernoulli/distribution/binomial.rb', line 36

def sample
  s = []
  @n.times do
    s << (rand < @p ? 1 : 0)
  end
  s
end

#sample_valueInteger Also known as: sv

Returns number of 1’s in a run of ‘#sample`.

Returns:

  • (Integer)

    number of 1’s in a run of ‘#sample`



45
46
47
# File 'lib/bernoulli/distribution/binomial.rb', line 45

def sample_value
  sample.count(1)
end

#skewnessObject



60
61
62
# File 'lib/bernoulli/distribution/binomial.rb', line 60

def skewness
  (1 - 2 * @p) / (Math.sqrt(@n * @p * (1 - @p)))
end

#to_sObject



24
25
26
# File 'lib/bernoulli/distribution/binomial.rb', line 24

def to_s
  "#<Distribution::Binomial @n=#@n, @p=#@p>"
end

#varianceObject Also known as: v



55
56
57
# File 'lib/bernoulli/distribution/binomial.rb', line 55

def variance
  @n * @p * (1 - @p)
end