Java Euclidean euclideanNorm(float vector[])

Here you can find the source of euclideanNorm(float vector[])

Description

euclidean Norm

License

Apache License

Declaration

public static float euclideanNorm(float vector[]) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static float euclideanNorm(float vector[]) {

        int n = vector.length;

        if (n < 1) {
            return 0;
        }//from   w  w  w  .j  a  v a 2s. c  o m

        if (n == 1) {
            return Math.abs(vector[0]);
        }

        // this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards

        double scale = 0; // scaling factor that is factored out
        double sum = 1; // basic sum of squares from which scale has been factored out
        for (int i = 0; i < n; i++) {
            if (vector[i] != 0) {
                double abs = Math.abs(vector[i]);
                // try to get the best scaling factor
                if (scale < abs) {
                    double t = scale / abs;
                    sum = 1 + sum * (t * t);
                    scale = abs;
                } else {
                    double t = abs / scale;
                    sum += t * t;
                }
            }
        }

        return (float) (scale * Math.sqrt(sum));
    }
}

Related

  1. euclideanGCD(final long firstNumerator, final long secondNumerator)
  2. euclideanGcd(long a, long b)
  3. euclideanLength(double[] vector)
  4. euclideanMod(final float x, final float y)
  5. euclideanNormSquared(double[] x1, double[] x2)