Skip to content

Instantly share code, notes, and snippets.

@kubo39
Created September 16, 2011 12:00
Show Gist options
  • Save kubo39/1221954 to your computer and use it in GitHub Desktop.
Save kubo39/1221954 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# Numericクラスを拡張
class Numeric
# 数値の二乗を計算するメソッド
# 返り値はfloat
def pow
self ** 2.0
end
end
# ピアソン相関係数を求めるプログラム
def pearson x, y
# 各関数の変数の数が同じ場合のみ求める
return false if x.length != y.length
n = x.length
vals = [*0..(n-1)]
# 単純な合計
sum_x = x.map(&:to_f).inject(&:+)
sum_y = y.map(&:to_f).inject(&:+)
# 平方の合計
sumx_square = x.map(&:pow).inject(&:+)
sumy_square = y.map(&:pow).inject(&:+)
# 積の合計
sum_x_y = vals.map {|idx| x[idx] * y[idx] }.inject(&:+)
# ピアソンスコアを算出
score = sum_x_y - (sum_x * sum_y / n)
den = ((sumx_square - sum_x**2/n)*(sumy_square - sum_y ** 2/n)) ** 0.5
# denが0なら0を返す
return 0 if den==0
# ピアソン相関係数を返す
r = score / den
end
# 実行部
if __FILE__ == $0
p pearson [1,2,3], [4,5,6]
p pearson [1,2,3], [4,4,4]
p pearson [1,2,3], [4,3,2]
end
@kubo39
Copy link
Author

kubo39 commented Sep 16, 2011

実行例

$ ruby pearson.rb
1.0
0
-1.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment