Itseez/opencv — pull request #2024 by pemmanuelviel (2013-12-19 23:18:40+00:00)
Title: when computing KMeans centers on non-real points, it's better to round instead of letting the compiler truncate the centers positions

Explanation:
dcenters[i][k] is a double, so why do we need to round it?
Because if Distance is belonging to the Integer space, "distance_" in the line below
DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
will truncate dcenters[j], so that's why we add or substract 0.5 (depends on the sign) to get the same result as round().

And why don't we use round() instead?
Because as the result is still stored in dcenters[i][k] that is a double, 6 for instance might be stored as 5.999999999

Finally, why don't we just create a template with a int result that will do the work like that:
DistanceType new_sq_dist = distance_(dataset_[indices[i]], roundTemplate(dcenters[j]), veclen_);
Because we are in an inner loop, so this will slow down process.