fix a bug in computing the gradient of distance function