in commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/twod/Vector2D.java [708:745]
private static Unit tryCreateNormalized(final double x, final double y, final boolean throwOnFailure) {
// Compute the inverse norm directly. If the result is a non-zero real number,
// then we can go ahead and construct the unit vector immediately. If not,
// we'll do some extra work for edge cases.
final double norm = Vectors.norm(x, y);
final double normInv = 1.0 / norm;
if (Vectors.isRealNonZero(normInv)) {
return new Unit(
x * normInv,
y * normInv);
}
// Direct computation did not work. Try scaled versions of the coordinates
// to handle overflow and underflow.
final double scaledX;
final double scaledY;
final double maxCoord = Math.max(Math.abs(x), Math.abs(y));
if (maxCoord > UNSCALED_MAX) {
scaledX = x * SCALE_DOWN_FACTOR;
scaledY = y * SCALE_DOWN_FACTOR;
} else {
scaledX = x * SCALE_UP_FACTOR;
scaledY = y * SCALE_UP_FACTOR;
}
final double scaledNormInv = 1.0 / Vectors.norm(scaledX, scaledY);
if (Vectors.isRealNonZero(scaledNormInv)) {
return new Unit(
scaledX * scaledNormInv,
scaledY * scaledNormInv);
} else if (throwOnFailure) {
throw Vectors.illegalNorm(norm);
}
return null;
}