I have a piece of code which includes this:
var clusterCenters = [{"x": 1,"y": 1},{"x": 10,"y": 10}];
console.log(clusterCenters);
In Chrome 26:
In Firefox 21:
Why does this error occur?
I guess the error has to be in the following function.
function getKMeansInfo(k, mouseX, mouseY) {
// choose cluster centers
var clusterCenters = [{"x": 1,"y": 1},{"x": 10,"y": 10}];
console.log(clusterCenters);
for (iteration=0;iteration< 20;iteration++) {
// for each object, check which cluster is nearest
for (i=0; i<points.length; i++) {
var distMin = 1000000;
var clusterMin = 0;
for(j=0; j<k; j++) {
var dist = euklideanDist(clusterCenters[j], points[i]);
if (dist < distMin) {
distMin = dist;
clusterMin = j
}
}
points[i]["cluster"] = clusterMin;
}
// calculate center of cluster
var clusterSum = new Array(k);
for (i=0; i<k; i++) {
clusterSum[i] = {"x":0, "y":0, "n":0};
}
for (i=0; i<points.length; i++) {
clusterSum[points[i]["cluster"]]["x"] += points[i]["cluster"]["x"];
clusterSum[points[i]["cluster"]]["y"] += points[i]["cluster"]["y"];
clusterSum[points[i]["cluster"]]["n"] += 1;
}
for (i=0; i<k; i++) {
if (clusterSum[i]["n"] > 0) {
clusterCenters[i] = {
"x":clusterSum[i]["x"]/clusterSum[i]["n"],
"y":clusterSum[i]["y"]/clusterSum[i]["n"]};
}
}
}
return {"cluster":1, "radius":10};
}
The full source is on GitHub.
edit: Only the complete example is still online.
Any recommendations for use of JavaScript are also welcome (I'm new to JavaScript).
I've just recognized that using floating point numbers in the example above gives less errors ... but the error still occurs. As I never divide through "x" or "y", but only through "n" (and I check if n is 0 bevore dividing) I don't see how I can get NaN.
console.log
implementations are sometimes "live". They don't necessarily represent the object when it was logged, but represent the object's "current state". You could check out all code that alters theclusterCenters
, especially the last loop where you divide values. There must be a non-number value there.