Angela - 1 year ago 78

Ruby Question

I have several records with a given attribute, and I want to find the standard deviation.

How do I do that?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
module Enumerable
def sum
self.inject(0){|accum, i| accum + i }
end
def mean
self.sum/self.length.to_f
end
def sample_variance
m = self.mean
sum = self.inject(0){|accum, i| accum +(i-m)**2 }
sum/(self.length - 1).to_f
end
def standard_deviation
return Math.sqrt(self.sample_variance)
end
end
```

Testing it:

```
a = [ 20, 23, 23, 24, 25, 22, 12, 21, 29 ]
a.standard_deviation
# => 4.594682917363407
```

*fixing "sample_variance" thanks to Dave Sag*

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**