Browse Source

Add new means (geometric, harmonic)

pull/2/head
Arthur POULET 4 years ago
parent
commit
89b1bfe430
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 2
      README.md
  2. 12
      spec/math/mean.cr
  3. 9
      src/lib/math/mean.cr

2
README.md

@ -69,6 +69,8 @@ Math.factorial(4) # => 24
[1, 2, 3].variance.round(4) # => 0.6667
[1, 2, 3].standard_deviation.round(4) # => 0.8165
[1, 2, 3].root_mean_square.round(2) # => 2.16
[2, 32].geometric_mean # => 8
[40, 60].harmonic_mean.round # => 48
```
## Development

12
spec/math/mean.cr

@ -15,4 +15,16 @@ describe Math::Mean do
[1, 2, 3, 2].root_mean_square.round(4).should eq(2.1213)
[1, 2, 1, 5, 10, 9, 1, -13, 2].root_mean_square.round(4).should eq(6.549)
end
it "test geometric mean" do
[2, 32].geometric_mean.should eq(8)
[10, 15].geometric_mean.round(2).should eq(12.25)
[5, 3, 12].geometric_mean.round(2).should eq(5.65)
[7, 9, 12].geometric_mean.round(2).should eq(9.11)
end
it "test harmonic mean" do
[1, 4, 1, 2].harmonic_mean.round(3).should eq(1.455)
[13, 23, 12, 44, 55].harmonic_mean.round(3).should eq(20.438)
end
end

9
src/lib/math/mean.cr

@ -10,6 +10,15 @@ module Math::Mean
def root_mean_square : Float64
Math.sqrt map { |e| e ** 2 }.mean
end
# For [a, b], a/c = c/b; c**2 = a*b
def geometric_mean : Float64
reduce { |l, r| l * r } ** (1.0 / size.to_f64)
end
def harmonic_mean : Float64
size.to_f64 / map { |e| 1.0 / e }.sum
end
end
module Enumerable(T)

Loading…
Cancel
Save