Find a centroid of a dataset

2.4k views Asked by At

If I have some random data set let's say

X       Y
1.2     16
5.7     0.256
128.54  6.879
0       2.87
6.78    0
2.98    3.7
...     ...
 x'      y'

How can I find the centroid coordinates of this data set?

p.s. Here what I tried but got wrong results

float Dim1[K];
float Dim2[K];
float centroidD1[K];
float centroidD2[K];

int K = 4;
int counter[K];
for(int i = 0; i < K ; i++)
{
    Dim1[i] = 0;
    Dim2[i] = 0;
    counter[i] = 0;
    for(int j = 0; j < hash["Cluster"].size(); j++)
    {
        if(hash["Cluster"].value(j) == i+1)
        {
            Dim1[i] += hash["Dim_1"].value(j);
            Dim2[i] += hash["Dim_2"].value(j);
            counter[i]++;
        }
    }
}

for(int l = 0; l < K; l++)
{
    centroidD1[l] = Dim1[l] / counter[l];
    centroidD2[l] = Dim2[l] / counter[l];
}

I guess I choose wrong algorithm for doing it, as I get wrong results.

1

There are 1 answers

0
Adam Burry On BEST ANSWER

Calculating a sum and dividing by N is not a good idea if you have a large data set. As your floating point accumulator grows adding a new point eventually stop working due to the magnitude difference. An incremental formula might work better, see: https://math.stackexchange.com/questions/106700/incremental-averageing

If the issue is too large a data set you can verify the basic functioning of your code by using a smaller data set with a hand verified result. For example, just 1 data point, or 10 data points.