find the standard deviation of a list of numbers in ruby

To find the standard deviation of a list of numbers in Ruby, you can use the Math module which provides a sqrt method for calculating the square roots of numbers.

Here's an example code snippet to find the standard deviation of a list of numbers in Ruby:

main.rb
def standard_deviation(numbers)
  n = numbers.length
  mean = numbers.sum(0.0) / n
  variance = numbers.inject(0.0) { |s, x| s + (x - mean)**2 } / n
  Math.sqrt(variance)
end

# Example usage
numbers = [2.5, 3.6, 4.7, 5.8, 6.9]
puts standard_deviation(numbers) #=> 1.995879023073232
283 chars
11 lines

In this code, the standard_deviation method takes an array of numbers as its parameter, calculates the mean of the list, computes the variance using the formula sum((x - mean)^2) / n, and finally returns the square root of the variance as the standard deviation.

gistlibby LogSnag