Permalink
Browse files

Added Calculator#merge

  • Loading branch information...
1 parent 3f9f2c8 commit 3682ca874416736ad1fe04b0a96565d1d1a8859b @delano committed Oct 6, 2009
Showing with 31 additions and 19 deletions.
  1. +23 −8 lib/benelux/stats.rb
  2. +8 −11 tryouts/10_stats_tryouts.rb
View
@@ -105,7 +105,7 @@ def merge(*tags)
mc.init_tags!
all = tags.empty? ? self : self.filter(tags)
all.each { |calc|
- mc.samples calc
+ mc.merge calc
mc.add_tags_quick calc.tags
}
mc
@@ -120,7 +120,7 @@ def filter(*tags)
end
# Based on Mongrel::Stats, Copyright (c) 2005 Zed A. Shaw
- class Calculator < Array
+ class Calculator
include Selectable::Object
attr_reader :sum, :sumsq, :n, :min, :max
@@ -130,25 +130,34 @@ def initialize
end
def +(other)
- self.push *other
- self.recalculate
- self
+ #self.push *other
+ #self.recalculate
+ #self
+ merge other
end
# Resets the internal counters so you can start sampling again.
def reset
@n, @sum, @sumsq = 0.0, 0.0, 0.0
- @last_time = 0.0
@min, @max = 0.0, 0.0
end
def samples(*args)
args.flatten.each { |s| sample(s) }
end
+ def merge(other)
+ @sum += other.sum
+ @sumsq += other.sumsq
+ @n += other.n
+ @min = other.min if other.min < @min
+ @max = other.max if other.max > @max
+ self
+ end
+
# Adds a sampling to the calculations.
def sample(s)
- self << s
+ #self << s
update s
end
@@ -198,7 +207,13 @@ def sd
return 0.0
end
end
-
+
+ def ==(other)
+ a=([@sum, @min, @max, @n, @sumsq] -
+ [other.sum, other.min, other.max, other.n, other.sumsq])
+ a.empty?
+ end
+
def recalculate
reset
self.each { |s| update(s) }
@@ -16,18 +16,15 @@
base
end
- dream :class, Benelux::Stats::Calculator
- #dream :n, 10
- #dream :sum, 45
- #dream :sumsq, 285
- #dream :min, 0
- #dream :max, 9
- #dream :proc, lambda { |calc| p calc.class }
+ dream true
drill "can add stats" do
- other = Benelux::Stats::Calculator.new
- 10.times { |i| other.sample(i) }
- other += base
- other
+ by_sample = Benelux::Stats::Calculator.new
+ 10.times { |i| by_sample.sample(i) }
+ by_sample += base
+ by_merge = base.merge(base)
+ stash :sample, by_sample
+ stash :merge, by_merge
+ by_sample == by_merge
end
end

0 comments on commit 3682ca8

Please sign in to comment.