private static Unit tryCreateNormalized()

in commons-geometry-euclidean/src/main/java/org/apache/commons/geometry/euclidean/threed/Vector3D.java [778:824]


        private static Unit tryCreateNormalized(final double x, final double y, final double z,
                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 = Math.sqrt((x * x) + (y * y) + (z * z));
            final double normInv = 1.0 / norm;
            if (Vectors.isRealNonZero(normInv)) {
                return new Unit(
                        x * normInv,
                        y * normInv,
                        z * 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 scaledZ;

            final double maxCoord = Math.max(Math.max(Math.abs(x), Math.abs(y)), Math.abs(z));
            if (maxCoord > UNSCALED_MAX) {
                scaledX = x * SCALE_DOWN_FACTOR;
                scaledY = y * SCALE_DOWN_FACTOR;
                scaledZ = z * SCALE_DOWN_FACTOR;
            } else {
                scaledX = x * SCALE_UP_FACTOR;
                scaledY = y * SCALE_UP_FACTOR;
                scaledZ = z * SCALE_UP_FACTOR;
            }

            final double scaledNormInv = 1.0 / Math.sqrt(
                    (scaledX * scaledX) +
                    (scaledY * scaledY) +
                    (scaledZ * scaledZ));

            if (Vectors.isRealNonZero(scaledNormInv)) {
                return new Unit(
                        scaledX * scaledNormInv,
                        scaledY * scaledNormInv,
                        scaledZ * scaledNormInv);
            } else if (throwOnFailure) {
                throw Vectors.illegalNorm(norm);
            }
            return null;
        }