lib/utils/mathutil.rb in stella-0.5.3 vs lib/utils/mathutil.rb in stella-0.5.4
- old
+ new
@@ -4,18 +4,21 @@
def self.variance(population)
n = 0
mean = 0.0
s = 0.0
+
population.each { |x|
n = n + 1
delta = (x - mean).to_f
mean = (mean + (delta / n)).to_f
s = (s + delta * (x - mean)).to_f
}
- return s / n
+ s / n
+ rescue => ex
+ 0.0
end
# calculate the standard deviation of a population
# accepts: an array, the population
# returns: the standard deviation
@@ -41,38 +44,48 @@
##
# Sum of all the elements of the Enumerable
def sum
- return self.inject(0) { |acc, i| acc + i }
+ return 0 if !self || self.empty?
+ self.inject(0) { |acc, i| acc.to_f + i.to_f }
end
##
# Average of all the elements of the Enumerable
#
# The Enumerable must respond to #length
def average
- return self.sum / self.length.to_f
+ return 0 unless self
+ self.sum / self.length.to_f
+ rescue => ex
+ 0.0
end
##
# Sample variance of all the elements of the Enumerable
#
# The Enumerable must respond to #length
def sample_variance
- avg = self.average
- sum = self.inject(0) { |acc, i| acc + (i - avg) ** 2 }
- return (1 / self.length.to_f * sum)
+ return 0 unless self
+ avg = self.average
+ sum = self.sum
+ (1 / self.length.to_f * sum)
+ rescue => ex
+ 0.0
end
##
# Standard deviation of all the elements of the Enumerable
#
# The Enumerable must respond to #length
def standard_deviation
- return Math.sqrt(self.sample_variance)
+ return 0 unless self
+ Math.sqrt(self.sample_variance)
+ rescue => ex
+ 0.0
end
end
\ No newline at end of file