Browse Source

Add variance / standard_deviation

pull/2/head
Arthur POULET 4 years ago
parent
commit
163ae26d66
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 9
      README.md
  2. 13
      spec/math/mean.cr
  3. 21
      spec/math/standard_deviation.cr
  4. 7
      src/lib/math/mean.cr
  5. 20
      src/lib/math/std_dev.cr

9
README.md

@ -64,6 +64,15 @@ Math.factorial(4) # => 24
```
### Series & Statistics
```crystal
[1.0, 2.0, 3.0].mean # => 2.0
[1.0, 2.0, 3.0].variance.round(4) # => 0.6667
[1.0, 2.0, 3.0].standard_deviation.round(4) # => 0.8165
```
## Development
- The lib is adapted to be usable with BigInt and BigFloat values

13
spec/math/mean.cr

@ -0,0 +1,13 @@
describe Math::Mean do
it "test mean on Array(Float64)" do
([] of Float64).mean.should eq 0.0
[1.0, 2.0, 3.0].mean.should eq 2.0
[1.0, 2.0, -3.0].mean.should eq 0.0
end
it "test mean on Array(Int32)" do
([] of Int32).mean.should eq 0.0
[1, 2, 3].mean.should eq 2.0
[1, 2, -3].mean.should eq 0.0
end
end

21
spec/math/standard_deviation.cr

@ -0,0 +1,21 @@
describe Math::StandardDeviation do
it "test variance & std dev explained" do
arr = [1, 2, 3, 4, 4]
mean = (4 + 4 + 3 + 2 + 1) / 5.0
variance = ((4 - mean)**2 + (4 - mean)**2 + (3 - mean)**2 + (2 - mean)**2 + (1 - mean)**2) / 5.0
standard_deviation = Math.sqrt(variance)
arr.mean.should eq(mean)
arr.variance.should eq(variance)
arr.standard_deviation.should eq(standard_deviation)
end
it "test standard deviation without explanations" do
arr = [1, 5, 23, 2, 0, 0, 1]
arr.mean.round(2).should eq 4.57
arr.variance.round(2).should eq 59.10
arr.standard_deviation.round(2).should eq 7.69
[1.0, 2.0, 3.0].variance.round(4).should eq(0.6667)
[1.0, 2.0, 3.0].standard_deviation.round(4).should eq(0.8165)
end
end

7
src/lib/math/mean.cr

@ -0,0 +1,7 @@
module Math::Mean
# Standard arithmetic mean
def mean : Float64
return 0.0_f64 if empty?
sum.to_f64 / size.to_f64
end
end

20
src/lib/math/std_dev.cr

@ -0,0 +1,20 @@
require "./mean"
module Math::StandardDeviation
include Math::Mean
# Squared deviation from the mean
def variance
mean = mean()
self.map { |e| (e - mean)**2 }.mean
end
# Population standard deviation
def standard_deviation
Math.sqrt variance
end
end
module Enumerable(T)
include Math::StandardDeviation
end
Loading…
Cancel
Save