Class: Keepit::Decaying

Inherits:
Object
  • Object
show all
Defined in:
lib/keepit/decaying.rb

Overview

A float value which decays exponentially toward 0 over time.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Decaying

opts - Hash

:p - Float (0.0) The initial value
:e - Float (Math::E) Exponent base
:r - Float (Math.log(0.5) / 10) Timescale factor - defaulting to decay 50% every 10 seconds


11
12
13
14
15
16
# File 'lib/keepit/decaying.rb', line 11

def initialize(opts = {})
  @p = opts[:p] || 0.0
  @e = opts[:e] || Math::E
  @r = opts[:r] || Math.log(0.5) / 10
  @t0 = Time.now.to_i
end

Instance Attribute Details

#eObject

Returns the value of attribute e.



4
5
6
# File 'lib/keepit/decaying.rb', line 4

def e
  @e
end

#pObject

Returns the value of attribute p.



5
6
7
# File 'lib/keepit/decaying.rb', line 5

def p
  @p
end

Instance Method Details

#<<(d) ⇒ Object

Add to current value

d - Float value to add



21
22
23
# File 'lib/keepit/decaying.rb', line 21

def <<(d)
  @p = value + d
end

#valueObject

Returns Float the current value (adjusted for the time decay)



26
27
28
29
30
31
32
# File 'lib/keepit/decaying.rb', line 26

def value
  return 0.0 unless @p > 0
  now = Time.now.to_i
  dt = now - @t0
  @t0 = now
  @p *= @e**(@r * dt)
end