Class: RV::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

Instance Method Summary collapse

Methods included from RV_Generator

#each

Constructor Details

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

Returns a new instance of Binomial.



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/random_variates.rb', line 457

def initialize(n: 1, p: 0.5, rng: U_GENERATOR)
  raise 'N must be an integer.' unless n.is_a? Integer
  raise 'N must be positive.' if n <= 0
  raise 'Require 0 < p < 1.' if p <= 0 || p >= 1

  @n = n.to_i
  @p = p
  @complement = false
  if @p <= 0.5
    @log_q = Math.log(1 - p)
  else
    @log_q = Math.log(@p)
    @complement = true
  end
  @rng = rng
end

Instance Attribute Details

#nObject (readonly)

Returns the value of attribute n.



455
456
457
# File 'lib/random_variates.rb', line 455

def n
  @n
end

#pObject (readonly)

Returns the value of attribute p.



455
456
457
# File 'lib/random_variates.rb', line 455

def p
  @p
end

Instance Method Details

#nextObject



474
475
476
477
478
479
480
481
482
# File 'lib/random_variates.rb', line 474

def next
  result = sum = 0
  loop do
    sum += Math.log(@rng.next) / (@n - result)
    break if sum < @log_q
    result += 1
  end
  @complement ? @n - result : result
end