Skip to content

Instantly share code, notes, and snippets.

@Alrecenk
Last active December 26, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alrecenk/7221196 to your computer and use it in GitHub Desktop.
Save Alrecenk/7221196 to your computer and use it in GitHub Desktop.
Normalizing a vector to length one, normalizing a data point into a distribution of mean zero and standard deviation of one, and generating a vector by a normal distribution. Different operations that are named similarly and might be confusion.
//makes a vector of length one
public static void normalize(double a[]){
double scale = 0 ;
for(int k=0;k<a.length;k++){
scale+=a[k]*a[k];
}
scale = 1/Math.sqrt(scale);
for(int k=0;k<a.length;k++){
a[k]*=scale ;
}
}
//scales points with the given mean and standard deviation to have mean of zero and deviation of one
public static void normalize(double a[], double mean[], double deviation[]){
for(int k=0;k<a.length;k++){
a[k] = (a[k]-mean[k])/deviation[k];
}
}
//returns a normally distributed random vector using the box muller transform
public static double[] normaldistribution(int dim, Random rand){
double[] axis = new double[dim];
//generate a normally distributed random vector using the Box-Muller transform to guarantee even distrubtion of directions
for (int k = 0; k < dim; k++){
axis[k] = Math.sqrt(-2 * Math.log(rand.nextDouble())) * Math.sin(2 * Math.PI * rand.nextDouble());
}
return axis;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment