Class: WalkerMethod
- Inherits:
-
Object
- Object
- WalkerMethod
- Defined in:
- lib/walker_method.rb,
lib/walker_method/version.rb
Constant Summary collapse
- VERSION =
"0.0.1"
Instance Attribute Summary collapse
-
#inx ⇒ Object
Returns the value of attribute inx.
-
#keys ⇒ Object
Returns the value of attribute keys.
-
#length ⇒ Object
Returns the value of attribute length.
-
#prob ⇒ Object
Returns the value of attribute prob.
-
#sumw ⇒ Object
Returns the value of attribute sumw.
-
#weights ⇒ Object
Returns the value of attribute weights.
Instance Method Summary collapse
-
#initialize(keys, weights) ⇒ WalkerMethod
constructor
A new instance of WalkerMethod.
- #random ⇒ Object
Constructor Details
#initialize(keys, weights) ⇒ WalkerMethod
Returns a new instance of WalkerMethod.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/walker_method.rb', line 6 def initialize(keys, weights) self.keys = keys self.weights = weights self.sumw = weights.reduce(&:+).to_f self.prob = [] self.inx = [] self.length = weights.length short = [] long = [] weights.each do |w| inx << -1 prob << w * length / sumw end prob.each.with_index do |p, index| short << index if p < 1 long << index if p > 1 end while short.length > 0 && long.length > 0 j = short.pop k = long[-1] inx[j] = k prob[k] -= (1 - prob[j]) if prob[k] < 1 short << k long.pop end end def random u = rand j = (rand * length).to_i if u <= prob[j] keys[j] else keys[inx[j]] end end end |
Instance Attribute Details
#inx ⇒ Object
Returns the value of attribute inx.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def inx @inx end |
#keys ⇒ Object
Returns the value of attribute keys.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def keys @keys end |
#length ⇒ Object
Returns the value of attribute length.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def length @length end |
#prob ⇒ Object
Returns the value of attribute prob.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def prob @prob end |
#sumw ⇒ Object
Returns the value of attribute sumw.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def sumw @sumw end |
#weights ⇒ Object
Returns the value of attribute weights.
4 5 6 |
# File 'lib/walker_method.rb', line 4 def weights @weights end |
Instance Method Details
#random ⇒ Object
36 37 38 39 40 41 42 43 44 |
# File 'lib/walker_method.rb', line 36 def random u = rand j = (rand * length).to_i if u <= prob[j] keys[j] else keys[inx[j]] end end |