Class: Gaussian

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

Overview

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) ⇒ Gaussian

Returns a new instance of Gaussian.



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/random_variates.rb', line 167

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|
    # Ratio of Uniforms
    bound = 2.0 * Math.sqrt(2.0 / Math::E)
    loop do
      u = rng.next
      next if u == 0.0

      v = bound * (rng.next - 0.5)
      x = v / u
      x_sqr = x * x
      u_sqr = u * u
      if 6.0 * x_sqr <= 44.0 - 72.0 * u + 36.0 * u_sqr - 8.0 * u * u_sqr
        yielder << sd * x + mean
      elsif x_sqr * u >= 2.0 - 2.0 * u_sqr
        next
      elsif x_sqr <= -4.0 * Math.log(u)
        yielder << sd * x + mean
      end
    end
  end
end

Instance Attribute Details

#meanObject (readonly)

Returns the value of attribute mean.



165
166
167
# File 'lib/random_variates.rb', line 165

def mean
  @mean
end

#sdObject (readonly)

Returns the value of attribute sd.



165
166
167
# File 'lib/random_variates.rb', line 165

def sd
  @sd
end