我正在写一个程序来计算c中的Pearson相关系数,但我遇到了一些麻烦,我不知道是什么问题,这里是我的代码:Pearson相关系数计算阵列
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define aSize 2000000
double mean(double* mean_array){
double mean = 0;
for (int i=0; i<aSize; i++){
mean = mean + mean_array[i];
}
mean = mean/aSize;
return mean;
}
double stan_dev_seq(double stan_array[], double stan_mean){
double a = 0;
for (int i=0; i<aSize; i++){
a = a + pow((stan_array[i]-stan_mean), 2);
}
a = a/aSize;
a = sqrt(a);
return a;
}
int pearson_seq(void){
clock_t begin, end;
double time_spent;
begin = clock();
double *a;
a = malloc(sizeof(double)*aSize);
double *b;
b = malloc(sizeof(double)*aSize);
double mean_a;
double mean_b;
for (int i=0; i<aSize; i++){
a[i] = sin(i);
b[i] = sin(i+2);
}
mean_a = mean(a);
mean_b = mean(b);
double stan_dev_a = stan_dev_seq(a, mean_a);
double stan_dev_b = stan_dev_seq(b, mean_b);
double pearson_numer;
for(int i=0; i<aSize; i++){
pearson_numer = pearson_numer + ((a[i]-mean_a)*(b[i]-mean_b));
}
pearson_numer = pearson_numer/aSize;
double pearson_coef = pearson_numer/(stan_dev_a*stan_dev_b);
printf("%s %G\n", "The Pearson Coefficient is: ", pearson_coef);
end = clock();
time_spent = (double)(end - begin)/CLOCKS_PER_SEC;
printf("%f %s\n", end, "ms");
printf("%f %s\n", begin, "ms");
printf("%f %s\n", time_spent, "ms");
free(a);
free(b);
return 0;
}
int main(void) {
pearson_seq();
return 0;
}
如果我运行该程序,我会得到一个不正确的系数值,然后出现seg错误,这对我来说确实没有意义。
如果我打印阵列我没有丝毫关系到数组的大小应该是什么让值的大小。
任何帮助,将不胜感激。
除了'sizeof'错误,您应该查看格式说明符。你需要'%zu'打印'size_t',sizeof'的'的结果类型,我相信当你尝试打印'clock_t'用'%F'发生赛格故障。 (编译器警告应该可以帮助您检测不匹配的格式说明符和参数。) –
发布的代码不会干净地编译!编译器提出了关于'的printf 2只问题陈述一个( “%F%S \ n” 个,结束, “MS”);'和一个约'的printf( “%F%S \ n” 个,开始, “MS”); '。编译时,始终启用所有警告(对于gcc,至少使用:'-Wall -Wextra -pedantic'),然后修复这些警告。 – user3629249
始终检查(!= NULL)从'malloc的返回值()',以确保操作成功 – user3629249