我正在通過「編程集體智慧」中的練習,但我正在使用JavaScript。我在Pearson Correlation算法中遇到了一些麻煩。這裏的功能:皮爾遜相關函數返回南
function rec(object1, object2) {
var sum1 = 0;
var sum2 = 0;
var squareSum1 = 0;
var squareSum2 = 0;
var productsSum = 0;
var i;
var commonKeys = commonProperties(object1, object2);
for (i = 0; i >= commonKeys.length; i += 1) {
sum1 += object1[commonKeys[i]];
sum2 += object2[commonKeys[i]];
squareSum1 += Math.pow(object1[commonKeys[i]], 2);
squareSum2 += Math.pow(object2[commonKeys[i]], 2);
productsSum += object1[commonKeys[i]] * object2[commonKeys[i]];
}
var num1 = productsSum - (sum1 * sum2/commonKeys.length);
var num2 = Math.sqrt((squareSum1 - (Math.pow(sum1, 2)/commonKeys.length)) * (squareSum2 - (Math.pow(sum2, 2)/commonKeys.length)));
return num1/num2;
}
完整的JSFiddle是here。我通過JSLint運行它,這就是爲什麼它可能有點混亂。任何人都知道什麼是錯的?
NUM1爲0,NUM2是0和0/0 = NaN的 –
你得到NaN的,因爲NUM2是0。它是不允許被零 – andreasnico
分你永遠不進入for循環'我
Jaco