R语言实现pearson相关系数的计算使用cor() 函数 默认使用pearson方法,我用c语言写了一段code实现,代码如下
#include <stdio.h>
#include <math.h>
#define TINY 1.0e-20
float pearsn(float x[], float y[], unsigned long n, float *r)
{
unsigned long j;
float yt,xt;
float t,df;
float syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
for (j=1;j<=n;j++) {
ax += x[j];
ay += y[j];
}
ax /= n;
ay /= n;
for (j=1;j<=n;j++) {
xt=x[j]-ax;
yt=y[j]-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
*r=sxy/(sqrt(sxx*syy)+TINY);
df=n-2;
return t=(*r)*sqrt(df/((1.0-(*r)+TINY)*(1.0+(*r)+TINY)));
}
int main() {
float number = 0;
unsigned long n = 5;
float x[5]={0.2,0.3,0.5,0.9,1.7};
float y[5]={7,9,8,4,1};
float *r = &number;
float *prob = &number;
float t=0;
t=pearsn(x,y,n,r);
printf("%f",*r);
return 0;
}
为什么与cor()的计算结果不一样呢?