class Stats
def initialize(aName)
@name = aName
self.reset
end
attr_reader :name, :maxx, :minx, :n, :sumy, :sumysq, :maxy, :miny
def reset
@sumy = @sumysq = 0.0
@n = 0
@sumx = @sumxsq = @sumxy = 0.0
@maxx = @minx = @maxy = @miny =nil
end
def mean
return nil if @n < 1
return @sumy.to_f / @n
end
def variance
return nil if @n < 2
ret = @n * @sumysq.to_f - @sumy * @sumy
return ret /= @n * (@n - 1)
end
def stddev
return nil if @n < 2
return Math.sqrt(variance)
end
def slope
return nil if @n < 1 || @sumxsq == 0
return (@n * @sumxy.to_f - @sumx * @sumy) / (@n * @sumxsq - (@sumx * @sumx))
end
def intercept
return nil if @n < 1 || @sumxsq == 0
return (@sumy - self.slope * @sumx)/@n
end
def correlation
t1 = (@n * @sumxsq.to_f - (@sumx * @sumx)) * (@n * @sumysq - (@sumy * @sumy))
return (@n * @sumxy - @sumx * @sumy) / Math.sqrt(t1)
end
def add(y, *xopt)
@sumy += y
@n += 1
@sumysq += y * y
@maxy = y if (!@maxy || y > @maxy)
@miny = y if (!@miny || y < @miny)
if !xopt || !xopt[0]
x = @n
else
x = xopt[0]
end
@sumx += x
@sumxsq += x * x
@sumxy += x * y
@maxx = x if (!@maxx || x > @maxx)
@minx = x if (!@minx || x < @minx)
return self
end
end
if __FILE__ == $0
def showStats(s)
puts "#{s.name}----------"
puts "\tn=#{s.n}\tmean=#{s.mean}\tsigma=#{s.stddev}"
puts "\tslope=#{s.slope}\tintercept=#{s.intercept}\n\tcorrelation=#{s.correlation}"
end
s = Stats.new("Correlation Test")
s.add(12,3).add(15,4).add(10,2.8).add(20,5.5)
showStats s
s = Stats.new("Auto Test")
s.add(12).add(15).add(20).add(24).add(22).add(28)
showStats s
s = Stats.new("Stress Test")
2000.times { s.add(rand(100)) }
showStats s
end
-- DaleBrayden - 07 Sep 2002