Here you can find the source of normalize(double[] v)
public static double[] normalize(double[] v)
//package com.java2s; //License from project: Open Source License public class Main { /**/*from ww w. j a v a2s.co m*/ * Renormalizes the array so that its L2 norm is 1 * (up to computational errors). */ public static double[] normalize(double[] v) { return (scalarMultiply(1.0 / norm(v), v)); } /** * Multiplies every component of an array by a scalar. */ public static double[] scalarMultiply(double a, double[] v) { double[] ans = new double[v.length]; for (int k = 0; k < v.length; k++) { ans[k] = a * v[k]; } return (ans); } /** * Multiplies every component of an array by a scalar. */ public static double[] scalarMultiply(double a, int[] v) { double[] ans = new double[v.length]; for (int k = 0; k < v.length; k++) { ans[k] = v[k] * a; } return (ans); } /** * Computes the L2 norm of an array (Euclidean norm or "length"). */ public static double norm(double[] data) { return (Math.sqrt(sumSquares(data))); } /** * Computes the L2 norm of an array (Euclidean norm or "length"). */ public static double norm(int[] data) { return (Math.sqrt(sumSquares(data))); } /** * Sums the squares of all components; * also called the energy of the array. */ public static double sumSquares(double[] data) { double ans = 0.0; for (int k = 0; k < data.length; k++) { ans += data[k] * data[k]; } return (ans); } /** * Sums the squares of all components; * also called the energy of the array. */ public static double sumSquares(double[][] data) { double ans = 0.0; for (int k = 0; k < data.length; k++) { for (int l = 0; l < data[k].length; l++) { ans += data[k][l] * data[k][l]; } } return (ans); } /** * Sums the squares of all components; * also called the energy of the array. */ public static int sumSquares(int[] data) { int ans = 0; for (int k = 0; k < data.length; k++) { ans += data[k] * data[k]; } return (ans); } /** * Sums the squares of all components; * also called the energy of the array. */ public static int sumSquares(int[][] data) { int ans = 0; for (int k = 0; k < data.length; k++) { for (int l = 0; l < data[k].length; l++) { ans += data[k][l] * data[k][l]; } } return (ans); } }