Class: RandomDistribution::DiscreteSequence

Inherits:
Sequence show all
Defined in:
lib/redshift/util/random.rb

Constant Summary

Constants included from Math

Math::Infinity

Instance Attribute Summary collapse

Attributes inherited from Sequence

#generator

Instance Method Summary collapse

Methods inherited from Sequence

random_pool_seed, random_seed, serial_count

Constructor Details

#initialize(opt = {}) ⇒ DiscreteSequence

Returns a new instance of DiscreteSequence.



197
198
199
200
201
202
203
204
205
206
207
# File 'lib/redshift/util/random.rb', line 197

def initialize opt = {}
  super
  @distrib = opt[:distrib] || { 0 => 1.0 }
  
  sum = @distrib.inject(0) {|sum, (pt, prob)| sum + prob}
  sum = sum.to_f # so division is ok
  
  @distrib.keys.each do |point|
    @distrib[point] /= sum
  end
end

Instance Attribute Details

#distribObject (readonly)

Returns the value of attribute distrib.



195
196
197
# File 'lib/redshift/util/random.rb', line 195

def distrib
  @distrib
end

Instance Method Details

#nextObject



209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/redshift/util/random.rb', line 209

def next
  loop do
    r = super
    @distrib.each do |point, probability|
      if r < probability
        return point
      end
      r -= probability
    end
    # repeat if failed to get a result (due to floating point imprecision)
  end
  ## this would be faster using an rbtree
end