Permalink
Browse files

Merge pull request #1 from lucianot/master

Included stdevp method
  • Loading branch information...
2 parents f310181 + 11def20 commit 5a2210d444392296e2475634f08f1978e6404752 @reu committed Apr 13, 2012
Showing with 47 additions and 1 deletion.
  1. +6 −1 README.md
  2. +22 −0 ext/standard_deviation/standard_deviation.c
  3. +19 −0 spec/standard_deviation/standard_deviation_spec.rb
View
@@ -18,13 +18,18 @@ Or install it yourself as:
## Usage
-Just call `standard_deviation` or `stdev` on a array with numbers.
+Just call `standard_deviation` or `stdev` on an array with numbers:
``` ruby
[1, 2, 3, 4, 5].stdev => 1.5811388300841898
[521.0, BigDecimal("1234.45"), 1_120].standard_deviation => 383.168958598336
```
+For population standard deviation, call `stdevp`:
+
+``` ruby
+[1, 2, 3, 4, 5].stdevp => 1.4142135623731
+```
## Benchmarks
@@ -22,7 +22,29 @@ static VALUE stdev(VALUE self) {
return rb_float_new(sqrt(variance / (size - 1)));
}
+static VALUE stdevp(VALUE self) {
+ int i, size;
+ double total, mean, variance;
+
+ size = RARRAY_LEN(self);
+ total = variance = 0;
+ VALUE *array = RARRAY_PTR(self);
+
+ for (i = 0; i < size; i++) {
+ total += NUM2DBL(array[i]);
+ }
+
+ mean = total / size;
+
+ for (i = 0; i < size; i++) {
+ variance += pow((NUM2DBL(array[i]) - mean), 2);
+ }
+
+ return rb_float_new(sqrt(variance / size));
+}
+
void Init_standard_deviation() {
rb_define_method(rb_cArray, "stdev", stdev, 0);
rb_define_alias(rb_cArray, "standard_deviation", "stdev");
+ rb_define_method(rb_cArray, "stdevp", stdev, 0);
}
@@ -19,4 +19,23 @@
it { should == 9.32559202767667 }
end
end
+
+ describe "#stdevp" do
+ subject { values.stdevp }
+
+ context "with integer values" do
+ let(:values) { [1, 2, 6, 3, -4, 23] }
+ it { should == 8.51306185941476 }
+ end
+
+ context "with float values" do
+ let(:values) { [1.0, 2.0, 6.0, 3.0, -4.0, 23.0] }
+ it { should == 8.51306185941476 }
+ end
+
+ context "with bigdecimal values" do
+ let(:values) { [BigDecimal("1.0"), BigDecimal("2.0"), BigDecimal("6.0"), BigDecimal("3.0"), BigDecimal("-4.0"), BigDecimal("23.0")] }
+ it { should == 8.51306185941476 }
+ end
+ end
end

0 comments on commit 5a2210d

Please sign in to comment.