Created
April 12, 2012 03:27
-
-
Save ohnishiakira/2364443 to your computer and use it in GitHub Desktop.
相関係数を求める
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# coding: utf-8 | |
# ref. http://ja.wikipedia.org/wiki/%E7%9B%B8%E9%96%A2%E4%BF%82%E6%95%B0 | |
# 相加平均 | |
def mean(x) | |
x.inject(:+) / x.length | |
end | |
# 共分散 | |
def covarience(x, y) | |
_x, _y = [x, y].map{|n| mean n} | |
x.zip(y).map{|xi, yi| (xi - _x) * (yi - _y)}.inject(:+) | |
end | |
# 標準偏差 | |
def deviation(d) | |
_d = mean d | |
Math.sqrt d.map{|i| (i - _d) ** 2}.inject(:+) | |
end | |
# 相関係数 | |
def correlation_coefficient(x, y) | |
covarience(x, y) / ( deviation(x) * deviation(y) ) | |
end | |
# ref. http://aoki2.si.gunma-u.ac.jp/lecture/Soukan/pearson.html | |
a = [2.8, 3.4, 3.6, 5.8, 7.0, 9.5, 10.2, 12.3, 13.2, 13.4] | |
b = [0.6, 3.0, 0.4, 1.5, 15.0, 13.4, 7.6, 19.8, 18.3, 18.9] | |
p correlation_coefficient(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment