Class: RubyStatistics::Distribution::Weibull

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-statistics/distribution/weibull.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(k, lamb) ⇒ Weibull

Returns a new instance of Weibull.



6
7
8
9
# File 'lib/ruby-statistics/distribution/weibull.rb', line 6

def initialize(k, lamb)
  self.shape = k.to_r
  self.scale = lamb.to_r
end

Instance Attribute Details

#scaleObject

k and lambda



4
5
6
# File 'lib/ruby-statistics/distribution/weibull.rb', line 4

def scale
  @scale
end

#shapeObject

k and lambda



4
5
6
# File 'lib/ruby-statistics/distribution/weibull.rb', line 4

def shape
  @shape
end

Instance Method Details

#cumulative_function(random_value) ⇒ Object



11
12
13
14
15
# File 'lib/ruby-statistics/distribution/weibull.rb', line 11

def cumulative_function(random_value)
  return 0 if random_value < 0

  1 - Math.exp(-((random_value/scale) ** shape))
end

#density_function(value) ⇒ Object



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

def density_function(value)
  return if shape <= 0 || scale <= 0
  return 0 if value < 0

  left = shape/scale
  center = (value/scale)**(shape - 1)
  right = Math.exp(-((value/scale)**shape))

  left * center * right
end

#meanObject



28
29
30
# File 'lib/ruby-statistics/distribution/weibull.rb', line 28

def mean
  scale * Math.gamma(1 + (1/shape))
end

#modeObject



32
33
34
35
36
# File 'lib/ruby-statistics/distribution/weibull.rb', line 32

def mode
  return 0 if shape <= 1

  scale * (((shape - 1)/shape) ** (1/shape))
end

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

Using the inverse CDF function, also called quantile, we can calculate a random sample that follows a weibull distribution.

Formula extracted from www.taygeta.com/random/weibull.html



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ruby-statistics/distribution/weibull.rb', line 49

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

  srand(seed)

  elements.times do
    results << ((-1/scale) * Math.log(1 - rand)) ** (1/shape)
  end

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

#varianceObject



38
39
40
41
42
43
# File 'lib/ruby-statistics/distribution/weibull.rb', line 38

def variance
  left = Math.gamma(1 + (2/shape))
  right = Math.gamma(1 + (1/shape)) ** 2

  (scale ** 2) * (left - right)
end