Module: NumericArray::InstanceMethods
- Defined in:
- lib/numeric_array.rb
Constant Summary collapse
- NUMERIC_REGEX =
/^-?\d+.?\d*e?-?\d*$/
Instance Method Summary collapse
-
#average ⇒ Object
(also: #avg, #mean)
average of an array of numbers.
- #check_numeric_array! ⇒ Object
- #non_numeric_elements ⇒ Object
- #numeric_array? ⇒ Boolean (also: #numeric?)
- #numerify ⇒ Object
- #numerify! ⇒ Object
- #sample_standard_deviation ⇒ Object (also: #sample_std_dev)
- #sample_variance ⇒ Object
-
#standard_deviation(sample = false) ⇒ Object
(also: #std_dev)
standard deviation of an array of numbers.
- #sum ⇒ Object
-
#variance(sample = false) ⇒ Object
variance of an array of numbers.
Instance Method Details
#average ⇒ Object Also known as: avg, mean
average of an array of numbers
13 14 15 16 17 |
# File 'lib/numeric_array.rb', line 13 def average check_numeric_array! a = numerify a.sum / length.to_f end |
#check_numeric_array! ⇒ Object
44 45 46 |
# File 'lib/numeric_array.rb', line 44 def check_numeric_array! raise ArgumentError, "Array cannot have the following non-numeric elements: #{non_numeric_elements.collect(&:inspect).join(", ")}" unless numeric_array? end |
#non_numeric_elements ⇒ Object
53 54 55 |
# File 'lib/numeric_array.rb', line 53 def non_numeric_elements self.select{|obj| !(obj.kind_of?(Numeric) or obj.to_s =~ NUMERIC_REGEX)} end |
#numeric_array? ⇒ Boolean Also known as: numeric?
48 49 50 |
# File 'lib/numeric_array.rb', line 48 def numeric_array? !self.detect{|obj| !(obj.kind_of?(Numeric) or obj.to_s =~ NUMERIC_REGEX) } end |
#numerify ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/numeric_array.rb', line 57 def numerify self.collect do |obj| if obj.kind_of? Numeric obj elsif obj.to_s =~ NUMERIC_REGEX obj.to_f else raise ArgumentError, "Array element #{obj.inspect} cannot be converted into a numeric value" end end end |
#numerify! ⇒ Object
69 70 71 |
# File 'lib/numeric_array.rb', line 69 def numerify! self.replace(numerify) end |
#sample_standard_deviation ⇒ Object Also known as: sample_std_dev
39 40 41 |
# File 'lib/numeric_array.rb', line 39 def sample_standard_deviation standard_deviation(true) end |
#sample_variance ⇒ Object
29 30 31 |
# File 'lib/numeric_array.rb', line 29 def sample_variance variance(true) end |
#standard_deviation(sample = false) ⇒ Object Also known as: std_dev
standard deviation of an array of numbers
34 35 36 |
# File 'lib/numeric_array.rb', line 34 def standard_deviation(sample = false) Math.sqrt(self.variance(sample)) end |
#sum ⇒ Object
6 7 8 9 10 |
# File 'lib/numeric_array.rb', line 6 def sum check_numeric_array! a = numerify a.inject(0) {|sum, value| sum + value} end |
#variance(sample = false) ⇒ Object
variance of an array of numbers
22 23 24 25 26 27 |
# File 'lib/numeric_array.rb', line 22 def variance(sample = false) a = numerify avg = a.average sum = a.inject(0) { |sum, value| sum + (value - avg) ** 2} (1 / (a.length.to_f - (sample ? 1 : 0)) * sum) end |