Sha256: 7dee019b4861d0a65c987222438acea3be542bbeb9eab0698b0b30a083c1e861

Contents?: true

Size: 1.08 KB

Versions: 5

Compression:

Stored size: 1.08 KB

Contents

# -*- coding: utf-8 -*-

class RailsDataExplorer
  module Statistics

    # Responsibilities:
    #  * Provide random numeric data, following a gaussian distribution.
    #
    # From http://stackoverflow.com/a/9266488
    class RngGaussian

      # @param mean [Float] the expected mean
      # @param sd [Float] the expected standard deviation
      # @param rng [Proc, optional] a random number generator
      def initialize(mean = 0.0, sd = 1.0, rng = lambda { Kernel.rand })
        @mean, @sd, @rng = mean, sd, rng
        @compute_next_pair = false
      end

      # Returns random numbers with a gaussian distribution.
      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
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rails-data-explorer-1.0.4 lib/rails_data_explorer/statistics/rng_gaussian.rb
rails-data-explorer-1.0.3 lib/rails_data_explorer/statistics/rng_gaussian.rb
rails-data-explorer-1.0.2 lib/rails_data_explorer/statistics/rng_gaussian.rb
rails-data-explorer-1.0.1 lib/rails_data_explorer/statistics/rng_gaussian.rb
rails-data-explorer-1.0.0 lib/rails_data_explorer/statistics/rng_gaussian.rb