我在C編程類中寫了一個程序來獲取2組實數的相關係數。我已經給出了方程,它引用了維基百科,所以我仔細檢查了那裏的方程。這裏是公式,這似乎是從我的研究非常標準的鏈接:Odd Pearson相關係數結果
我寫的程序,但是當我跑了我得到的數字比1我的結果時,我知道這是不正確的。我查了幾遍代碼,但找不到任何不合適的地方,所以我試着用n除以n而不是n,這給了我預期的-1到1範圍的值,所以我測試了它針對我在網上找到的數據值以及相關係數計算器(http://easycalculation.com/statistics/correlation.php),現在我得到了我輸入的所有數字的正確結果。我無法弄清楚這是爲什麼,所以我想我可以在這裏得到一些幫助。這裏是我的程序代碼,如果還有什麼突出的,我在這裏做錯了,我很想聽聽一些建議,但主要是我試圖找出爲什麼我得到正確的結果與出現是一個錯誤的等式。
然後它將讀取兩個數組(x和y)的值,然後計算兩組數字之間的相關係數。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int n; /* value to determine array length */
/* declare variables to hold results for each equation for x and y
initialize all to zero to prepare for summation */
float r = 0.0, xbar = 0.0, ybar = 0.0, sx = 0.0, sy = 0.0;
/*get number n input from user */
printf("Please enter a number n: ");
scanf("%d", &n);
if(n < 1) {
printf("n must be a positive number.\nPlease enter a new value: ");
scanf("%d", &n);
if(n < 1) {
printf("Invalid input, exiting...\n");
return 0;
}
}
/*initialize arrays x and y with length of n */
float x[n], y[n];
/*use for loop to read in values of x*/
int i;
for(i = 0; i < n; ++i) {
printf("Please enter a number for x: ");
scanf("%f", &x[i]);
}
/*use for loop to read in values of y*/
for(i = 0; i < n; ++i) {
printf("Please enter a number for y: ");
scanf("%f", &y[i]);
}
/*compute xbar */
for(i = 0; i < n; ++i) {
xbar += x[i];
}
xbar /= n;
/*compute ybar*/
for(i = 0; i < n; ++i) {
ybar += y[i];
}
ybar /= n;
/* compute standard deviation of x*/
for(i = 0; i < n; ++i) {
sx += (x[i] - xbar) * (x[i] - xbar);
}
sx = sqrt((sx/n));
/* compute standard deviation of y */
for(i = 0; i < n; ++i) {
sy += (y[i] - ybar) * (y[i] - ybar);
}
sy = sqrt((sy/n));
/*compute r, the correlation coefficient between the two arrays */
for(i = 0; i < n; ++i) {
r += (((x[i] - xbar)/sx) * ((y[i] - ybar)/sy));
}
r /= (n); /* originally divided by n-1, but gave incorrect results
dividing by n instead produces the desired output */
/* print results */
printf("The correlation coefficient of the entered lists is: %6.4f\n", r);
return 0;
}
(它看起來像我的代碼格式不工作,對此深表遺憾。使用標籤和按鈕嘗試,但不能弄明白。它看起來像我得到了它有些工作,比以前更好。)
你能發佈格式化的代碼嗎?這將使它更容易遵循。 – Mick 2010-01-28 09:34:21
您是否嘗試過使用'double'或甚至'long double'而不是'float'? – kennytm 2010-01-28 09:34:39
@David:新的格式比以前更糟::(縮進4個空格或1個標籤來標記一段代碼,在發佈之前查看預覽 – kennytm 2010-01-28 09:39:14