Class: ERV::GammaDistribution

Inherits:
Distribution show all
Defined in:
lib/erv/gamma_distribution.rb

Overview

We refer to the formulation of the Gamma distribution adopted by [KROESE11]:

f(x) = fraclambda^{alpha x^- 1 e^x}Gamma(alpha)

with alpha > 0 being the shape parameter, lambda > 0 being the scale parameter, and x > 0.

(Note that, unlike [KROESE11] Wikipedia refers to the beta parameter as the “rate”.)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ GammaDistribution

Returns a new instance of GammaDistribution.

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/erv/gamma_distribution.rb', line 16

def initialize(opts={})
  super(opts)

  raise ArgumentError unless opts[:scale] and opts[:shape]
  @scale = opts[:scale].to_f
  @shape = opts[:shape].to_f

  raise ArgumentError, "scale parameter must be greater than zero!" unless @scale > 0.0
  raise ArgumentError, "shape parameter must be greater than zero!" unless @shape > 0.0

  @mean = @shape / @scale
  @variance = @shape / (@scale ** 2)
end

Instance Attribute Details

#meanObject

Returns the value of attribute mean.



14
15
16
# File 'lib/erv/gamma_distribution.rb', line 14

def mean
  @mean
end

#varianceObject

Returns the value of attribute variance.



14
15
16
# File 'lib/erv/gamma_distribution.rb', line 14

def variance
  @variance
end

Instance Method Details

#sampleObject

We use Marsaglia and Tsang’s sampling algorithm

For more details, see [KROESE11], section 4.2.6, algorithm 4.33 and www.hongliangjie.com/2012/12/19/how-to-generate-gamma-random-variables/



34
35
36
# File 'lib/erv/gamma_distribution.rb', line 34

def sample
  gamrand(@shape, @scale)
end