S2uniform.R

richard — Feb 15, 2014, 9:05 PM

## Uniform random points on sphere generated using "trig method"
## (method 3) of Dave Seaman:
## http://www.math.niu.edu/~rusin/known-math/96/sph.rand
## http://mathforum.org/kb/message.jspa?messageID=393612

## (a) Choose z uniformly distributed in [-1,1].
## (b) Choose t uniformly distributed on [0, 2*pi).
## (c) Let r = sqrt(1-z^2).
## (d) Let x = r * cos(t).
## (e) Let y = r * sin(t).

N <- 1000
z <- runif(N, -1, 1)
t <- runif(N, 0, 2*pi)
r <- sqrt(1 - z^2)
x <- r * cos(t)
y <- r * sin(t)

library(lattice)
cloud(z ~ x+y)

plot of chunk unnamed-chunk-1


## To really see that it works, run this script in your
## console window. The plot3d() command opens up a window
## with a 3-D scatter plot that you can rotate by hand

library(rgl)
plot3d(x, y, z)

## Back to library "lattice"
## 3-D surface parametrized on a 2-D grid 

n <- 50

tx <- matrix(seq(-pi, pi, length.out = 2*n), 2*n, n) 
ty <- matrix(seq(-pi, pi, length.out = n) / 2, 2*n, n, byrow = T) 
xx <- cos(tx) * cos(ty) 
yy <- sin(tx) * cos(ty) 
zz <- sin(ty) 

wireframe(zz ~ xx + yy) 

plot of chunk unnamed-chunk-1