Class: BoxMuller

Inherits:
Object
  • Object
show all
Includes:
RV_Generator
Defined in:
lib/random_variates.rb

Overview

Alternate Gaussian/normal random variate generator with specified mean and standard deviation. Defaults to a standard normal.

Arguments
  • mean -> the expected value (default: 0).

  • sd -> the standard deviation (default: 1).

  • rng -> the (Enumerable) source of U(0, 1)‘s (default: U_GENERATOR)

Instance Attribute Summary collapse

Attributes included from RV_Generator

#generator

Instance Method Summary collapse

Methods included from RV_Generator

#each, #next

Constructor Details

#initialize(mean: 0.0, sd: 1.0, rng: U_GENERATOR) ⇒ BoxMuller



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/random_variates.rb', line 208

def initialize(mean: 0.0, sd: 1.0, rng: U_GENERATOR)
  raise 'Standard deviation must be positive.' if sd <= 0

  @mean = mean
  @sd = sd
  @generator = Enumerator.new do |yielder|
    # Box-Muller
    next_z = 0.0
    need_new_pair = false
    loop do
      need_new_pair ^= true
      if need_new_pair
        theta = 2.0 * Math::PI * rng.next
        d = sd * Math.sqrt(-2.0 * Math.log(rng.next))
        next_z = mean + d * Math.sin(theta)
        yielder << mean + d * Math.cos(theta)
      else
        yielder << next_z
      end
    end
  end
end

Instance Attribute Details

#meanObject (readonly)

Returns the value of attribute mean.



206
207
208
# File 'lib/random_variates.rb', line 206

def mean
  @mean
end

#sdObject (readonly)

Returns the value of attribute sd.



206
207
208
# File 'lib/random_variates.rb', line 206

def sd
  @sd
end