Skip to content

Instantly share code, notes, and snippets.

@cmdrkeene
Created April 24, 2012 22:06
Show Gist options
  • Save cmdrkeene/2484215 to your computer and use it in GitHub Desktop.
Save cmdrkeene/2484215 to your computer and use it in GitHub Desktop.
Ruby Calc
class Calc
MINUTE = 60
HOUR = 3600
DAY = 86400
WEEK = 604800
class << self
def time_of_day_weighted(value, time = Time.now.utc)
value.to_f * (time.seconds_since_midnight / DAY)
end
def percent_difference(x1, x2)
x1, x2 = x1.to_f, x2.to_f
((x1 - x2) / ((x1 + x2)/2)).abs * 100.0
end
def percent_change(x1, x2)
return 0 if x1 == 0
x1, x2 = x1.to_f, x2.to_f
((x2 - x1) / x1) * 100.0
end
# Pass sample=true if you only pass a subset of population
def variance(population, sample = false)
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 sample
s / (n - 1)
else
s / n
end
end
def standard_deviation(population, sample = false)
Math.sqrt(variance(population, sample))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment