Here you can find the source of normalize(final double[] vec)
Parameter | Description |
---|---|
vec | the vector to normalize |
public static boolean normalize(final double[] vec)
//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; } }