Class: Croupier::Distributions::Normal

Inherits:
Croupier::Distribution show all
Defined in:
lib/croupier/distributions/normal.rb

Overview

Normal Distribution Continuous distribution (mu,sigma) (defaults to (0,1) ) where mu is the mean and sigma the standard deviation.

Instance Attribute Summary

Attributes inherited from Croupier::Distribution

#description, #name, #parameters

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Croupier::Distribution

#configure, #generate_number

Constructor Details

#initialize(options = {}) ⇒ Normal

Returns a new instance of Normal.



11
12
13
14
15
# File 'lib/croupier/distributions/normal.rb', line 11

def initialize(options={})
  @name = "Uniform distribution"
  @description = "Continuous distribution (mu,sigma) (defaults to (0,1) ) where mu is the mean and sigma the standard deviation."
  configure(options)
end

Class Method Details

.cli_nameObject



42
43
44
# File 'lib/croupier/distributions/normal.rb', line 42

def self.cli_name
  "normal"
end

.cli_optionsObject



46
47
48
49
50
51
52
53
# File 'lib/croupier/distributions/normal.rb', line 46

def self.cli_options
  {:options => [
     [:mean, 'mean of the distribution', {:type=>:float, :default => 0.0}],
     [:std, 'standard deviation of the distribution', {:type=>:float, :default => 1.0}]
   ],
   :banner => "Normal distribution. Generate numbers following a continuous distribution the real line with mean :mean and standard deviation :std."
  }
end

Instance Method Details

#default_parametersObject



38
39
40
# File 'lib/croupier/distributions/normal.rb', line 38

def default_parameters
  {:mean => 0, :std => 1}
end

#generate_sample(n = 1) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/croupier/distributions/normal.rb', line 17

def generate_sample(n=1)
  sample = n.odd? ? n+1 : n

  # Generate
  gen = (1..sample).map do |x|
    1 - rand # because uniform need to be in (0,1]
  end.each_slice(2).flat_map do |x, y|
    [
      Math.sqrt(-2*Math.log(x)) * Math.cos(2*Math::PI*y),
      Math.sqrt(-2*Math.log(x)) * Math.sin(2*Math::PI*y)
    ]
  end

  # Adjust parameters.
  gen.map!{ |x| x * @parameters[:std] }  if @parameters[:std] != 1
  gen.map!{ |x| x + @parameters[:mean] } if @parameters[:mean] != 0

  # Adjust length
  n.odd? ? gen[0..-2] : gen
end