Trevor Berg: The Blog

Avatar

Standard Deviation and Correlation Coefficient in ruby

I recently had to write a few math functions for some Filtered Averaging stuff. I thought somebody else out there might find them useful

def std_dev(list)

  # Calculate neccesary values
  list_squared = list.map {|item| item*item }
  n = list.size

  #Calculate the std deviation
  right = (Float (sum(list)**2))/n

  ((Float (sum(list_squared)) - right) / (n-1)) ** 0.5

end

def correlation(x, y)

  # Calculate the necessary values
  n = x.size

  sum_x = sum(x)
  sum_y = sum(y)

  x_squared = x.map {|item| item*item }
  y_squared = y.map {|item| item*item }

  sum_x_squared = sum(x_squared)
  sum_y_squared = sum(y_squared)

  xy = []
  x.each_with_index do |value, key|
    xy << value * y[key]
  end

  sum_xy = sum(xy)

  # Calculate the correlation value
  left = n * sum_xy - sum_x * sum_y
  right = ((n * sum_x_squared - sum_x**2) * (n * sum_y_squared - sum_y**2)) ** 0.5

  left / right
end

def sum(list)
  list.inject( nil ) { |sum,x| sum ? sum+x : x };
end