Class: RandomDistribution::Sequence

Inherits:
Object
  • Object
show all
Includes:
Math
Defined in:
lib/redshift/util/random.rb

Overview

Base class for sequences that sample different kinds of distributions. The actual PRNG must be plugged in at initialization, or else ruby’s global PRNG is used.

Defined Under Namespace

Classes: RubyGlobalGenerator

Constant Summary collapse

@@have_dev_random =

assume so until evidence to contrary

true

Constants included from Math

Math::Infinity

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opt = {}) ⇒ Sequence

Options are :seed and :generator.

The :generator must either have a method #next that returns a float between 0 and 1, or a method #new that returns an instance that has such a #next method.

If generator is not given, uses ruby’s Kernel#rand (beware global state) and the :seed option.



32
33
34
35
36
37
38
39
# File 'lib/redshift/util/random.rb', line 32

def initialize opt = {}
  gen = opt[:generator] || RubyGlobalGenerator
  if gen.respond_to?(:new)
    @generator = gen.new(opt[:seed])
  else
    @generator = gen
  end
end

Instance Attribute Details

#generatorObject (readonly)

Returns the value of attribute generator.



21
22
23
# File 'lib/redshift/util/random.rb', line 21

def generator
  @generator
end

Class Method Details

.random_pool_seedObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/redshift/util/random.rb', line 55

def self.random_pool_seed
  ## could also get random data from net
  if @@have_dev_random
    @random_pool ||= ""
    if @random_pool.length < 4
      File.open('/dev/random') do |dr|
        if select([dr],nil,nil,0)
          @random_pool << dr.sysread(100)
        end
      end
    end
    if @random_pool.length >= 4
      @random_pool.slice!(-4..-1).unpack('L')[0]
    end
  end
rescue SystemCallError
  @@have_dev_random = false
end

.random_seedObject

A utility method for getting a random seed.



47
48
49
50
51
# File 'lib/redshift/util/random.rb', line 47

def self.random_seed
  Sequence.random_pool_seed ||
    ((Time.now.to_f * 1_000_000_000).to_i % 1_000_000_000) +
    Sequence.serial_count + Process.pid
end

.serial_countObject



41
42
43
44
# File 'lib/redshift/util/random.rb', line 41

def self.serial_count
  @count ||= 0
  @count += 1
end

Instance Method Details

#nextObject



74
75
76
# File 'lib/redshift/util/random.rb', line 74

def next
  @generator.next
end