class RV::Binomial

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)

Attributes

n[R]
p[R]

Public Class Methods

new(n: 1, p: 0.5, rng: U_GENERATOR) click to toggle source
# File lib/random_variates.rb, line 464
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

Public Instance Methods

next() click to toggle source
# File lib/random_variates.rb, line 481
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