title: How to calculate the centroids in k-means++ by using distances?
body: <p>I am using the k-means++ clusterer from Apache Commons Math in a interactive genetic algorithm to reduce the number of individuals that are evaluated by the user.</p>
  
  <p>Commons Math makes it very easy to use. The user only needs to implement the 
  <a href="http://commons.apache.org/math/api-2.1/org/apache/commons/math/stat/clustering/Clusterable.html" rel="nofollow"><code>Clusterable</code></a> interface. It has two methods:</p>
  
  <p><code>double distanceFrom(T p)</code> which is quite clear and <code>T  centroidOf(Collection&lt;T&gt; p)</code>, which lets the user pick the centroid of a cluster.</p>
  
  <p>If used on euclidean points, the centroid is very easy to calculate. But on chromosomes it is quite difficult, because their meaning is not always clear.</p>
  
  <p>My question: Is there a efficient generic way to pick the centroid, not depending on the problem domain? (E.g. by using the distance)</p>
  
  <hr>
  
  <p>EDIT</p>
  
  <p>Ok, here is now my code for the centroid calculation. 
  The idea: The point that has the lowest total distance to all other points is the nearest to the centroid.</p>
  
  <pre><code>public T centroidOf(Collection&lt;T&gt; c) {
    double minDist = Double.MAX_VALUE;
    T minP = null;
  
    // iterate through c
    final Iterator&lt;T&gt; it = c.iterator();
    while (it.hasNext()) {
      // test every point p1
      final T p1 = it.next();
      double totalDist = 0d;
      for (final T p2 : c) {
        // sum up the distance to all points p2 | p2!=p1
        if (p2 != p1) {
          totalDist += p1.distanceFrom(p2);
        }
      }
  
      // if the current distance is lower that the min, take it as new min
      if (totalDist &lt; minDist) {
        minDist = totalDist;
        minP = p1;
      }
    }
    return minP;
  }
  </code></pre>