Class: Bernoulli::Distribution::Binomial
- Inherits:
-
Object
- Object
- Bernoulli::Distribution::Binomial
- 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
- #excess ⇒ Object
- #expected_value ⇒ Object (also: #ev)
-
#initialize(n, p) ⇒ Binomial
constructor
A new instance of Binomial.
-
#probability(k) ⇒ Float
The probability of ‘k` successes.
-
#sample ⇒ Array<0, 1>
Preform a binomial experiment of length ‘@n` and probability `@p`.
-
#sample_value ⇒ Integer
(also: #sv)
Number of 1’s in a run of ‘#sample`.
- #skewness ⇒ Object
- #to_s ⇒ Object
- #variance ⇒ Object (also: #v)
Methods included from Bernoulli::Distribution
#[], #probability_range, #standard_deviation
Constructor Details
#initialize(n, p) ⇒ Binomial
Returns a new instance of Binomial.
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
#excess ⇒ Object
64 65 66 |
# File 'lib/bernoulli/distribution/binomial.rb', line 64 def excess (1 - 6 * @p * (1 - @p)) / (@n * @p * (1 - @p)) end |
#expected_value ⇒ Object 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.
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 |
#sample ⇒ Array<0, 1>
Preform a binomial experiment of length ‘@n` and probability `@p`
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_value ⇒ Integer Also known as: sv
Returns 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 |
#skewness ⇒ Object
60 61 62 |
# File 'lib/bernoulli/distribution/binomial.rb', line 60 def skewness (1 - 2 * @p) / (Math.sqrt(@n * @p * (1 - @p))) end |
#to_s ⇒ Object
24 25 26 |
# File 'lib/bernoulli/distribution/binomial.rb', line 24 def to_s "#<Distribution::Binomial @n=#@n, @p=#@p>" end |
#variance ⇒ Object Also known as: v
55 56 57 |
# File 'lib/bernoulli/distribution/binomial.rb', line 55 def variance @n * @p * (1 - @p) end |