我正在进行“编程集体智能”的练习,但我使用的是javascript。皮尔逊相关算法有点问题。功能如下:

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中运行了它,这就是为什么它可能有点混乱有人知道怎么了吗?

最佳答案

你在条件“for”中犯了一个小错误,var“i”永远不会超过commonkeys。

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;
}

https://jsfiddle.net/98uoy87u/2/
它工作得很好,给出“-1”作为答案。
再见。

09-26 01:10