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