fixed errors in distance calculations, safeguard against divisions by zero (Math.max(N, 0.1))