Optimization of the distance function