Java Array Normalize normalize(final double[] vec)

Here you can find the source of normalize(final double[] vec)

Description

Normalize a vector, i.e.

License

Open Source License

Parameter

Parameter Description
vec the vector to normalize

Return

false if the vector summed to 0, true else

Declaration

public static boolean normalize(final double[] vec) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/* www.j a  v a2s.  co m*/
     * Normalize a vector, i.e. divide each component by the sum of all the
     * components. If the sum is 0, the vector is not modified and the method
     * returns false.
     * Precondition : vec != null
     * @param vec    the vector to normalize
     * @return false if the vector summed to 0, true else
     */
    public static boolean normalize(final double[] vec) {
        assert vec != null;

        final double sum = sum(vec);
        if (sum != 0.) {
            for (int i = 0; i < vec.length; i++) {
                vec[i] /= sum;
            }
            assert sum(vec) == 1.;
            return true;
        }
        return false;
    }

    /**
    * Computes the sum of the elements of a vector.
    * @param array  the array, to be summed.
    * @return       the sum of the elements of the vector.
    */
    public static double sum(final double[] vec) {
        assert vec != null;

        double s = 0;
        for (double i : vec) {
            s += i;
        }
        return s;
    }
}

Related

  1. normalize(final byte[] input, final int bit)
  2. normalize(final double[] a)
  3. normalize(final double[] doubles)
  4. normalize(final double[] fir)
  5. normalize(final double[] tab)
  6. normalize(final double[] vector, final double[] minima, final double[] maxima)
  7. normalize(float p[])
  8. normalize(float[] data)
  9. normalize(float[] in)