相関係数

統計

概要

 閲覧数:1349  投稿日: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



タグ


sqrt 





PHPでExcelの統計関数を実装



週間人気ページランキング / 3-22 → 3-28
順位 ページタイトル抜粋 アクセス数
1 後ろから3文字削除 / 「18:00:00」→「18:00」 | 文字列(テキスト処理) 34
2 null代入とunset()の違い | 変数 15
3 「input type="datetime-local"」で受け取った文字列をハイフンへ変更 | 日付および時刻関連 13
4 現在WebページのURLパスを第2階層まで取得 | パス 12
4 指定文字列より前を取得 | 文字列(テキスト処理) 12
5 URLから、トップページ(index.html)判定 | ルーティング 11
6 PHPコード 10
7 本日が「第何何曜日」の当日に該当するか、を判定 | 日付および時刻関連 7
8 Smarty(テンプレートエンジン) カテゴリー 6
9 配列キー内に「指定文字列が含まれるキー」と「その値」を抽出して、新しい配列を返す | 配列(型) 5
10 特定のHTMLタグのみ(aタグは除く)表示を許可 | エスケープ処理 4
10 foreachの中でswitch文 | 配列(型) 4
10 配列の内容(ひらがな)を、読み(あ行~わ行)で分け、新たな配列へ格納 | 配列(型) 4
11 マテリアルカラーをランダムに3色取得 / 重複なし | 色 3
11 Smartyのテンプレートにincludeしたファイルを表示 | Smarty(テンプレートエンジン) 3
11 realpath(__DIR__) | パス 3
11 URL抽出 | PCRE — 正規表現 (Perl 互換)(テキスト処理) 3
11 セッションIDを指定文字列へ変更 | セッション 3
11 変数名の一部だけを可変にする | 可変変数(変数) 3
12 PHPバージョン表示 | サーバー情報および実行時の環境情報 2
2023/3/29 1:01 更新