Class: RailsDataExplorer::Statistics::RngGaussian

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_data_explorer/statistics/rng_gaussian.rb

Overview

Responsibilities:

* Provide random numeric data, following a gaussian distribution.

From stackoverflow.com/a/9266488

Instance Method Summary collapse

Constructor Details

#initialize(mean = 0.0, sd = 1.0, rng = lambda { Kernel.rand }) ⇒ RngGaussian

Returns a new instance of RngGaussian.

Parameters:

  • mean (Float) (defaults to: 0.0)

    the expected mean

  • sd (Float) (defaults to: 1.0)

    the expected standard deviation

  • rng (Proc, optional) (defaults to: lambda { Kernel.rand })

    a random number generator



15
16
17
18
# File 'lib/rails_data_explorer/statistics/rng_gaussian.rb', line 15

def initialize(mean = 0.0, sd = 1.0, rng = lambda { Kernel.rand })
  @mean, @sd, @rng = mean, sd, rng
  @compute_next_pair = false
end

Instance Method Details

#randObject

Returns random numbers with a gaussian distribution.



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rails_data_explorer/statistics/rng_gaussian.rb', line 21

def rand
  if (@compute_next_pair = !@compute_next_pair)
    # Compute a pair of random values with normal distribution.
    # See http://en.wikipedia.org/wiki/Box-Muller_transform
    theta = 2 * Math::PI * @rng.call
    scale = @sd * Math.sqrt(-2 * Math.log(1 - @rng.call))
    @g1 = @mean + scale * Math.sin(theta)
    @g0 = @mean + scale * Math.cos(theta)
  else
    @g1
  end
end