Class: RV::Binomial
- Inherits:
-
Object
- Object
- RV::Binomial
- 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
-
#n ⇒ Object
readonly
Returns the value of attribute n.
-
#p ⇒ Object
readonly
Returns the value of attribute p.
Instance Method Summary collapse
-
#initialize(n: 1, p: 0.5, rng: U_GENERATOR) ⇒ Binomial
constructor
A new instance of Binomial.
- #next ⇒ Object
Methods included from RV_Generator
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
#n ⇒ Object (readonly)
Returns the value of attribute n.
465 466 467 |
# File 'lib/random_variates.rb', line 465 def n @n end |
#p ⇒ Object (readonly)
Returns the value of attribute p.
465 466 467 |
# File 'lib/random_variates.rb', line 465 def p @p end |
Instance Method Details
#next ⇒ Object
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 |