Class: Binomial

Inherits:
Object
  • Object
show all
Includes:
RV_Generator
Defined in:
lib/random_variates.rb

Overview

Binomial generator. Number of “successes” in n independent trials.

Arguments
  • n -> the number of trials (p > 0, integer; default: 1).

  • p -> the probability of success (0 < p < 1; default: 0.5).

  • rng -> the (Enumerable) source of U(0, 1)‘s (default: U_GENERATOR)

Instance Attribute Summary collapse

Attributes included from RV_Generator

#generator

Instance Method Summary collapse

Methods included from RV_Generator

#each, #next

Constructor Details

#initialize(n: 1, p: 0.5, rng: U_GENERATOR) ⇒ Binomial

Returns a new instance of Binomial.



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/random_variates.rb', line 414

def initialize(n: 1, p: 0.5, rng: U_GENERATOR)
  raise 'N must be a positive integer.' if n.to_i != n || n <= 0
  raise 'Require 0 < p < 1.' if p <= 0 || p >= 1

  @n = n.to_i
  @p = p
  log_q = Math.log(1 - p)
  @generator = Enumerator.new do |yielder|
    loop do
      result = sum = 0
      loop do
        sum += Math.log(rng.next) / (n - result)
        break if sum < log_q

        result += 1
      end
      yielder << result
    end
  end
end

Instance Attribute Details

#nObject (readonly)

Returns the value of attribute n.



412
413
414
# File 'lib/random_variates.rb', line 412

def n
  @n
end

#pObject (readonly)

Returns the value of attribute p.



412
413
414
# File 'lib/random_variates.rb', line 412

def p
  @p
end