Browse Source

Add correlation coef

pull/2/head v0.2.1
Arthur POULET 4 years ago
parent
commit
69f3647119
No known key found for this signature in database GPG Key ID: FC154EA63FF5D8BC
  1. 8
      README.md
  2. 12
      spec/math/correlation.cr
  3. 25
      src/lib/math/correlation.cr

8
README.md

@ -74,6 +74,14 @@ Math.factorial(4) # => 24
[1,2,3,2,1].macd 3 # => [2.0, 2.333, 2.0]
```
### Correlations
```crystal
[1,2,3,4].covariance [4,2,1,0] # => -1.625
[1,2,3,4].correlation_coef [1,2,3,3] + 1 > 1.5 # => true
[1,2,3,4].correlation_coef [-14,14,101,-100] + 1 > 1.5 # => false
```
## Development
- The lib is adapted to be usable with BigInt and BigFloat values

12
spec/math/correlation.cr

@ -0,0 +1,12 @@
describe Math::Correlation do
it "test basic confidence interval" do
arr1 = [1, 2, 2.5, 3, 3.5, 3.8, 4, 4.2, 4.4, 4.5]
arr2 = [1, 2, 3, 4, 5, 6.5, 8, 10, 12, 15]
arr1.mean.round(4).should eq 3.29
arr2.mean.round(4).should eq 6.65
arr1.size.should eq 10
arr2.size.should eq 10
arr1.covariance(arr2).round(4).should eq 4.2215
arr1.correlation_coef(arr2).round(4).should eq 0.8906
end
end

25
src/lib/math/correlation.cr

@ -0,0 +1,25 @@
require "./std_dev"
module Math::Correlation
# Computes the correlation coefficient with another list
def correlation_coef(rhs : Enumerable)
raise "Impossible to computes the covariance for #{rhs.size} list (require #{size})" if rhs.size != size
e = self.standard_deviation * rhs.standard_deviation
covariance(rhs) / e
end
# Computes the covariance with another list
def covariance(rhs : Enumerable)
raise "Impossible to computes the covariance for #{rhs.size} list (require #{size})" if rhs.size != size
e = self.mean * rhs.mean
self.zip(rhs).map do |t|
x = t[0]
y = t[1]
x*y - e
end.mean
end
end
module Enumerable(T)
include Math::Correlation
end
Loading…
Cancel
Save