一般在计算相关系数时都要遍历4次数据,这在数据比较多,需要读写文件时,显然是费时的。这里给出Single Pass版本的计算方法,但是其中的变化依据还没有搞懂,希望各位指教:
伪代码:

 1 sum_sq_x = 0
 2 sum_sq_y = 0
 3 sum_coproduct = 0
 4 mean_x = x[1]
 5 mean_y = y[1]
 6 for i in 2 to N:
 7     sweep = (i - 1.0/ i
 8     delta_x = x[i] - mean_x
 9     delta_y = y[i] - mean_y
10     sum_sq_x += delta_x * delta_x * sweep
11     sum_sq_y += delta_y * delta_y * sweep
12     sum_coproduct += delta_x * delta_y * sweep
13     mean_x += delta_x / i
14     mean_y += delta_y / i 
15 pop_sd_x = sqrt( sum_sq_x / N )
16 pop_sd_y = sqrt( sum_sq_y / N )
17 cov_x_y = sum_coproduct / N
18 correlation = cov_x_y / (pop_sd_x * pop_sd_y)
19

下面是我用C改写的,这份改写同时放在了Wiki上面:
 1#include "stdlib.h"
 2#include "math.h"
 3void SinglePassCorrelation(FILE *file,int N)
 4{
 5    double *x=new double[N+1];
 6    double *y=new double[N+1];
 7    int i;
 8    for(i=1;i<=N;i++)
 9    {
10        fscanf(file,"%lf %lf",&x[i],&y[i]);
11        printf("%10.6f %10.6f\n",x[i],y[i]);
12    }

13    double sum_sq_x=0;
14    double sum_sq_y=0;
15    double sum_coproduct=0;
16    double mean_x=x[1];
17    double mean_y=y[1];
18    double sweep=0;
19    double delta_x;
20    double delta_y;
21    double pop_sd_x;
22    double pop_sd_y;
23    double cov_x_y;
24    double correlation;
25    for(i=2;i<=N;i++)
26    {
27        sweep=(i-1.0)/i;
28        delta_x=x[i]-mean_x;
29        delta_y=y[i]-mean_y;
30        sum_sq_x+=delta_x*delta_y*sweep;
31        sum_sq_y+=delta_y*delta_y*sweep;
32        sum_coproduct+=delta_x*delta_y*sweep;
33        mean_x+=delta_x/i;
34        mean_y+=delta_y/i;
35    }
//end for i
36    pop_sd_x=sqrt(sum_sq_x/N);
37    pop_sd_y=sqrt(sum_sq_y/N);
38    cov_x_y=sum_coproduct/N;
39    correlation=cov_x_y/(pop_sd_x*pop_sd_y);
40}

41
Posted on 2008-11-28 20:13 邹敏 阅读(2051) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理