Class: ERV::BetaDistribution

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

Constant Summary

Constants inherited from Distribution

Distribution::DEFAULT_SEED

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ BetaDistribution

Returns a new instance of BetaDistribution.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/erv/beta_distribution.rb', line 5

def initialize(opts = {})
  raise ArgumentError, 'alpha is required' unless opts[:alpha]
  raise ArgumentError, 'beta is required' unless opts[:beta]
  raise ArgumentError, 'alpha must be greater than zero' unless opts[:alpha].to_f > 0.0
  raise ArgumentError, 'beta must be greater than zero' unless opts[:beta].to_f > 0.0

  # Parameters alpha and beta must be greater than zero
  @alpha = opts[:alpha]
  @beta = opts[:beta]

  @gamma_alpha = GammaDistribution.new(shape: @alpha, scale: 1.0)
  @gamma_beta  = GammaDistribution.new(shape: @beta, scale: 1.0)
end

Instance Method Details

#meanObject



28
29
30
# File 'lib/erv/beta_distribution.rb', line 28

def mean
  @alpha.to_f / (@alpha + @beta)
end

#sampleObject

The handbook describes many method to sample from a Beta distribution. We could use Gamma RVs or event sampling u ~ N(0,1) and then X = U ** (1 / alpha)



21
22
23
24
25
26
# File 'lib/erv/beta_distribution.rb', line 21

def sample
  # let's use gamma random variables
  x = @gamma_alpha.sample
  y = @gamma_beta.sample
  x / (x + y)
end

#varianceObject



32
33
34
# File 'lib/erv/beta_distribution.rb', line 32

def variance
  (@alpha.to_f * @beta) / (((@alpha + @beta)**2) * (@alpha + @beta + 1))
end