Sha256: 253ee7eafb223e87ae90e651b61597e815b836c7625591af940996d7d91ae509

Contents?: true

Size: 822 Bytes

Versions: 14

Compression:

Stored size: 822 Bytes

Contents

require 'active_support/core_ext/enumerable' # For Array#sum

module MoreCoreExtensions
  module ArrayMath
    #
    # Returns the mean of an Array of Numerics.
    #
    #   [1, 2, 3, 4, 5].mean  #=> 3.0
    #   [1.0, 2.0, 3.0].mean  #=> 2.0
    def mean
      sum.to_f / length
    end

    #
    # Returns the standard deviation of an Array of Numerics.
    #
    #   [1, 2, 3, 4, 5].stddev  #=> 1.5811388300841898
    #   [1.0, 2.0, 3.0].stddev  #=> 1.0
    def stddev
      Math.sqrt(variance)
    end

    #
    # Returns the variance of an Array of Numerics.
    #
    #   [1, 2, 3, 4, 5].variance  #=> 2.5
    #   [1.0, 2.0, 3.0].variance  #=> 1.0
    def variance
      μ = mean
      reduce(0) { |m, i| m + (i - μ).square } / (length - 1)
    end
  end
end

Array.send(:include, MoreCoreExtensions::ArrayMath)

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
more_core_extensions-4.3.1 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-4.3.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-4.2.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-4.1.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-4.0.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.8.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.7.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.6.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.5.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.4.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.3.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.2.0 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.1.1 lib/more_core_extensions/core_ext/array/math.rb
more_core_extensions-3.1.0 lib/more_core_extensions/core_ext/array/math.rb