Class: Statistics::Distribution::Normal

Inherits:
Object
  • Object
show all
Defined in:
lib/statistics/distribution/normal.rb

Direct Known Subclasses

StandardNormal

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(avg, std) ⇒ Normal

Returns a new instance of Normal.



7
8
9
10
11
# File 'lib/statistics/distribution/normal.rb', line 7

def initialize(avg, std)
  self.mean = avg.to_f
  self.standard_deviation = std.to_f
  self.variance = std.to_f**2
end

Instance Attribute Details

#meanObject Also known as: mode

Returns the value of attribute mean.



4
5
6
# File 'lib/statistics/distribution/normal.rb', line 4

def mean
  @mean
end

#standard_deviationObject

Returns the value of attribute standard_deviation.



4
5
6
# File 'lib/statistics/distribution/normal.rb', line 4

def standard_deviation
  @standard_deviation
end

#varianceObject

Returns the value of attribute variance.



4
5
6
# File 'lib/statistics/distribution/normal.rb', line 4

def variance
  @variance
end

Instance Method Details

#cumulative_function(value) ⇒ Object



13
14
15
# File 'lib/statistics/distribution/normal.rb', line 13

def cumulative_function(value)
  (1/2.0) * (1.0 + Math.erf((value - mean)/(standard_deviation * Math.sqrt(2.0))))
end

#density_function(value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/statistics/distribution/normal.rb', line 17

def density_function(value)
  return 0 if standard_deviation <= 0

  up_right = (value - mean)**2.0
  down_right = 2.0 * variance
  right = Math.exp(-(up_right/down_right))
  left_down = Math.sqrt(2.0 * Math::PI * variance)
  left_up = 1.0

  (left_up/(left_down) * right)
end

#random(elements: 1, seed: Random.new_seed) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/statistics/distribution/normal.rb', line 35

def random(elements: 1, seed: Random.new_seed)
  results = []

  # Setup seed
  srand(seed)

  # Number of random numbers to be generated.
  elements.times do
    x, y, r = 0.0, 0.0, 0.0

    # Find an (x, y) point in the x^2 + y^2 < 1 circumference.
    loop do
      x = 2.0 * rand - 1.0
      y = 2.0 * rand - 1.0

      r = (x ** 2) + (y ** 2)

      break unless r >= 1.0 || r == 0
    end

    # Project the random point to the required random distance
    r = Math.sqrt(-2.0 * Math.log(r) / r)

    # Transform the random distance to a gaussian value and append it to the results array
    results << mean + x * r * standard_deviation
  end

  if elements == 1
    results.first
  else
    results
  end
end