Created
February 23, 2009 20:56
-
-
Save drio/69171 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Basic Statistical Methods Module | |
# accepts: an array, the population/list | |
# returns: Result of running the measure (std_dev, mean, median) | |
# | |
module StatisticalTools | |
def self.std_dev(population) | |
n = 0 | |
mean = 0.0 | |
s = 0.0 | |
population.each do |x| | |
n = n + 1 | |
delta = x - mean | |
mean = mean + (delta / n) | |
s = s + delta * (x - mean) | |
end | |
Math.sqrt(s/n) | |
end | |
def self.mean(list) | |
Float (list.inject {|sum, i| sum += i } / list.size) | |
end | |
def self.median(list) | |
list.sort! | |
n = (list.length - 1) / 2 | |
n2 = (list.length) / 2 | |
list.length % 2 == 0 ? (list[n] + list[n2]) / 2 : list[n] | |
end | |
def self.sum(list) | |
list.inject( nil ) { |sum,x| sum ? sum+x : x }; | |
end | |
end | |
# | |
# Main | |
# | |
if !$test && __FILE__ == $0 | |
puts "Great running ..." | |
# Tests | |
elsif __FILE__ == $0 | |
require 'test/unit' | |
class Test_StatisticalTools < Test::Unit::TestCase | |
def setup | |
@list_even = %w(2 4 4 4 5 5 7 9).map {|i| i.to_f} | |
@list_odd = %w(1 3 24 17 12 6 14).map {|i| i.to_f} | |
@list_other = %w(1 2 3 4 5).map {|i| i.to_f} | |
end | |
def two_two(float_n) | |
sprintf("%2.2f", float_n) | |
end | |
def test_mean | |
assert_equal(5.00, StatisticalTools::mean(@list_even)) | |
end | |
def test_std_dev | |
assert_equal(2, StatisticalTools::std_dev(@list_even)) | |
assert_equal("7.60", two_two(StatisticalTools::std_dev(@list_odd))) | |
end | |
def test_median | |
assert_equal(2, StatisticalTools::std_dev(@list_even)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment