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.



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/random_variates.rb', line 467

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.



465
466
467
# File 'lib/random_variates.rb', line 465

def n
  @n
end

#pObject (readonly)

Returns the value of attribute p.



465
466
467
# File 'lib/random_variates.rb', line 465

def p
  @p
end

Instance Method Details

#nextObject



484
485
486
487
488
489
490
491
492
# File 'lib/random_variates.rb', line 484

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