概要
閲覧数:1706
投稿日:2014-05-14
更新日:2014-05-14
相関係数
コード
function corrcoef($var_x, $var_y) { $mean_x = NULL; $mean_y = NULL; $sum_sq_x = NULL; $sum_sq_y = NULL; $sum_coproduct = NULL; if (!count($var_x) || !is_array($var_x)) die('配列じゃない・・・'); if (!count($var_y) || !is_array($var_y)) die('配列じゃない・・・'); $c = (count($var_x) > count($var_y)) ? count($var_x) : count($var_y); $c = 0; while (true) { //Notice: Undefined offsetとなるので変更 // if (is_null($var_x[$c]) || is_null($var_y[$c])) break; if (!isset($var_x[$c]) || !isset($var_y[$c])) break; $_var_x[] = $var_x[$c]; $_var_y[] = $var_y[$c]; $c++; } if ( isset( $_var_x[$c] ) ){ $mean_x = (float) $_var_x[$c]; } if ( isset( $_var_y[$c] ) ){ $mean_y = (float) $_var_y[$c]; } $n = 0; while ($n < $c) { if (is_null($_var_x[$n]) || is_null($_var_y[$n])) break; $n = (float) $n; $sweep = $n / ($n + 1.0); $float_x = (float) $_var_x[$n]; $float_y = (float) $_var_y[$n]; $delta_x = $float_x - $mean_x; $delta_y = $float_y - $mean_y; $sum_sq_x += $delta_x * $delta_x * $sweep; $sum_sq_y += $delta_y * $delta_y * $sweep; $sum_coproduct += $delta_x * $delta_y * $sweep; $mean_x += $delta_x / ($n + 1.0); $mean_y += $delta_y / ($n + 1.0); $n += 1; } $n = (float) $n; $pop_sd_x = sqrt($sum_sq_x / $n); $pop_sd_y = sqrt($sum_sq_y / $n); $cov_x_y = $sum_coproduct / $n; $result = $cov_x_y / ($pop_sd_x * $pop_sd_y); return $result; } for ($i=0; $i<=100; $i++) { $ary1[] = rand(0, 100); $ary2[] = rand(0, 100); } print corrcoef($ary1, $ary2);
結果
0.12244969945723