Stddev

From EggeWiki
Revision as of 03:22, 20 October 2009 by Brianegge (talk | contribs) (Created page with 'This handy script calcs the standard deviation of a list of numbers from the standard input. Example: <geshi lang="bash"> ping google.com | ruby -ne 'if $_ =~ /time(\d+)ms/ the…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

This handy script calcs the standard deviation of a list of numbers from the standard input. Example:

<geshi lang="bash"> ping google.com | ruby -ne 'if $_ =~ /time(\d+)ms/ then puts $1 end' | stddev count mean stddev 4 48.33 34.39 </geshi>

<geshi lang="ruby">

  1. !/bin/env ruby

def variance(population)

 n = 0
 mean = 0.0
 s = 0.0
 population.each { |x|
   n = n + 1
     delta = x - mean
     mean = mean + (delta / n)
     s = s + delta * (x - mean)
 }
  1. if you want to calculate std deviation
  2. of a sample change this to "s / (n-1)"
 return s / n

end

def mean(population)

 n = 0
 mean = 0.0
 population.each { |x|
   n = n + 1
     delta = x - mean
     mean = mean + (delta / n)
 }
 return mean

end

  1. calculate the standard deviation of a population
  2. accepts: an array, the population
  3. returns: the standard deviation

def standard_deviation(population)

 Math.sqrt(variance(population))

end

values = [] $<.each do |l|

values << l.to_f

end

puts ["count", "mean", "stddev"].join("\t") puts "%d\t%.2f\t%.2f" % [values.size(), mean(values), standard_deviation(values)] </geshi>