Class: Starter::Random::Sequence
- Inherits:
-
Object
- Object
- Starter::Random::Sequence
- Includes:
- Math
- Defined in:
- lib/starter/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.
Direct Known Subclasses
ConstantSequence, DiscreteSequence, ExponentialSequence, GaussianSequence, LogNormalSequence, UniformSequence
Defined Under Namespace
Classes: RubyGlobalGenerator
Constant Summary collapse
- @@have_dev_random =
assume so until evidence to contrary
true
Instance Attribute Summary collapse
-
#generator ⇒ Object
readonly
Returns the value of attribute generator.
Class Method Summary collapse
- .random_pool_seed ⇒ Object
-
.random_seed ⇒ Object
A utility method for getting a random seed.
- .serial_count ⇒ Object
Instance Method Summary collapse
-
#initialize(opt = {}) ⇒ Sequence
constructor
Options are :seed and :generator.
- #next ⇒ Object
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.
40 41 42 43 44 45 46 47 |
# File 'lib/starter/random.rb', line 40 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
#generator ⇒ Object (readonly)
Returns the value of attribute generator.
29 30 31 |
# File 'lib/starter/random.rb', line 29 def generator @generator end |
Class Method Details
.random_pool_seed ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/starter/random.rb', line 63 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_seed ⇒ Object
A utility method for getting a random seed.
55 56 57 58 59 |
# File 'lib/starter/random.rb', line 55 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_count ⇒ Object
49 50 51 52 |
# File 'lib/starter/random.rb', line 49 def self.serial_count @count ||= 0 @count += 1 end |
Instance Method Details
#next ⇒ Object
82 83 84 |
# File 'lib/starter/random.rb', line 82 def next @generator.next end |