Created
September 12, 2010 18:25
-
-
Save jamster/576305 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # bunch of stats functions for quick usage in arrays... hobbled together from myself and a bunch of blogs... | |
| module Stats | |
| def sumitup | |
| if self.class == Hash | |
| sum = self.inject(0){|total, item| total = total + (item[1] || 0); total} | |
| end | |
| if self.class == Array | |
| sum = self.inject(0){|total, item| total = total + (item || 0); total} | |
| end | |
| sum | |
| end | |
| def average | |
| the_sum = Float(sumitup ? sumitup : 0) | |
| the_length = Float(self.length) | |
| the_sum / the_length | |
| end | |
| def median | |
| numbers = self.class == Hash ? self.values : self | |
| n = (numbers.length - 1) / 2 # Middle of the array | |
| n2 = (numbers.length) / 2 # Other middle of the array. | |
| # Used only if amount in array is even | |
| if numbers.length % 2 == 0 # If number is even | |
| median = (numbers[n] + numbers[n2]) / 2 | |
| else | |
| median = numbers[n] | |
| end | |
| return median | |
| end | |
| def mode | |
| numbers = self.class == Hash ? self.values : self | |
| c_n_count = 0 # Current number count | |
| length = numbers.length - 1 | |
| amount = {} # New array for the number of times each number occurs in the array | |
| for x in 0..length | |
| c_number = numbers[x] | |
| for y in 0..length | |
| if numbers[y] == c_number # If the current number is | |
| # equal to the upper level current number | |
| c_n_count = c_n_count + 1 | |
| end | |
| end | |
| amount[x] = c_n_count # Add the total number of occurences in the value array | |
| c_n_count = 0 | |
| end | |
| max = 0 | |
| high_number = 0 | |
| for x in 0..length | |
| if amount[x] > max # If the current number breaks the previous high record | |
| max = amount[x] # Reset the max to this new record | |
| high_number = x # Set the new most common number to that number | |
| end | |
| end | |
| return numbers[high_number] | |
| end | |
| def variance | |
| population = self.class == Hash ? self.values : self | |
| 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) | |
| } | |
| # if you want to calculate std deviation | |
| # of a sample change this to "s / (n-1)" | |
| return s / n | |
| end | |
| # calculate the standard deviation of a population | |
| # accepts: an array, the population | |
| # returns: the standard deviation | |
| def standard_deviation | |
| Math.sqrt(variance) | |
| end | |
| end | |
| class Array | |
| include Stats | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment