Created
November 8, 2011 02:48
-
-
Save rondale-sc/1346872 to your computer and use it in GitHub Desktop.
Down and Dirty Stats
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
require 'bigdecimal' | |
require 'csv' | |
require 'pp' | |
class Stats | |
include Enumerable | |
def initialize(array) | |
standardize_array(array) | |
end | |
def to_csv(file_path) | |
file_path ||= "./stats.csv" | |
CSV.open(file_path, "w") do |csv| | |
csv << ["Results"] | |
@array.each do |result| | |
csv << [result.to_s("F")] | |
end | |
end | |
end | |
def standardize_array(array) | |
@array = [] | |
array.map do |element| | |
if element.class == BigDecimal then next | |
elsif element.class == Fixnum then @array << BigDecimal.new(element.to_s) | |
elsif element.class == Float then @array << BigDecimal.new(element.to_s) | |
elsif element.class == String && element =~ /\A\d+(\.|)\d+\z/ then @array << BigDecimal.new(element) | |
else raise StandardError, "Incompatible elements provided." | |
end | |
end | |
end | |
def <<(element) | |
@array << element | |
standardize_array(@array) | |
end | |
def sum | |
@array.inject(BigDecimal.new("0")) {|memo,item| memo + item } | |
end | |
def mean | |
sum / @array.length | |
end | |
def sample_variance | |
@array.inject(BigDecimal.new("0")) { |memo,element| memo += (element - mean) ** 2 } / BigDecimal.new((@array.length - 1).to_s) | |
end | |
def standard_deviation | |
Math.sqrt(sample_variance) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment