Below is the syntax highlighted version of Sphere.java
from §9.8 Data Analysis.
/****************************************************************************** * Compilation: javac Sphere.java * Execution: java Sphere N * Dependencies StdRandom.java * * Computes a random point on the surface of an N-dimensional sphere * with radius 1 using Brown's method. Brown's method is to compute * N independent variables x[0], ..., x[N-1] from a standard Gaussian * distribution. Then * * ( x[0]/r, x[1]/r, ..., x[N-1]/r ) * * has the desired distribution, where r = sqrt(x[0]^2 + ... + x[N-1]^2). * * * % java Sphere 1 * 1.0 * * % java Sphere 1 * -1.0 * * % java Sphere 2 * -0.2239806529364283 * 0.9745935907393252 * * % java Sphere 5 * 0.953736056675788 * 0.2233325012832955 * 0.15023547754201239 * 0.13387920998076436 * -0.00397322157886321 * ******************************************************************************/ public class Sphere { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double[] x = new double[N]; double r = 0.0; // generate N variables from Gaussian distribution for (int i = 0; i < N; i++) x[i] = StdRandom.gaussian(); // compute Euclidean norm of vector x[] for (int i = 0; i < N; i++) r = r + x[i]*x[i]; r = Math.sqrt(r); // print scaled vector for (int i = 0; i < N; i++) StdOut.println(x[i] / r); } }