Anda di halaman 1dari 1

# # # # # #

Program to generate a random sample of n points distributed uniformly on the surface of a d-dimensional hypersphere with radius r centred at the origin in d dimensions. This script illustrates the function using scatterplots for varying sizes of 'n' for 2nd and 3rd dimensions and records the observations in a PDF file.

# Ref. 1: http://en.wikipedia.org/wiki/N-sphere # Ref. 2: Donald Knuth, The Art of Computing, Vol. 2, 3rd ed., Sec. 3.4.1.E.6 # Created on: Nov 28, 2010 # Ankit Dangi, CMS 1010, ankit@cms.unipune.ac.in # Function returns a (n x d) matrix, with each row # representing the d-dimensional coordinates # one random point from the hypersphere. runif.sphere <- function(n, d = 3, r = 1) { # generate (n x d) random numbers using normal distribution M <- matrix(rnorm(n * d), nrow = n, ncol = d); # compute the radius as euclidean norm r <- apply(M, MARGIN = 1, FUN = function(x) { return (sqrt(sum(x * x))); }); # obtain the diagonal matrix of the computed radius d <- diag(1/r); # return the (n x d) matrix after dividing each number # of the matrix by the radius (i.e. the diagonal matrix) return (d %*% M); } # to record the graphical results in a PDF file pdf(file = '2.pdf', title = 'Illustration of Runif Sphere', onefile = T, width = 11.7, height = 8.3, paper = 'a4r'); # set the plotting region as square (for circle to look like one) # set the mfcol for a grid of size 2x4 (for better assessment) par(pty = 's', mfcol = c(2, 4)); # observe runif.sphere by looping for varying sizes of n for (i in 1:4) { # vary the size of n with ith powers of 10 n <- (10 ^ i); # demonstrate the function (as intended) by making a simple # X-Y scatterplot with varying 'n' for d = 2 X <- runif.sphere(n, 2); # plot the obtained (n x d) matrix plot(X, main = paste('X-Y Scatterplot for n = ', n)); # demonstrate the function (as intended) by making a simple # X-Y-Z scatterplot with varying 'n' for d = 3 X <- runif.sphere(n, 3); # plot the obtained (n x d) matrix using 'scatterplot3d' package scatterplot3d(X, main = paste('X-Y-Z Scatterplot for n = ', n)); } # reset the plotting region as maximal par(pty = 'm') # turn off the 'pdf' graphical output device dev.off();

Anda mungkin juga menyukai