Random vectors on a sphere
This Python module rndsphere can be used to generate random cartesian vectors equally distributed on the surface of a sphere. It uses the so called Sphere Point Picking algorithm.
__author__ = 'Manuel Metz, mmetz @ astro.uni-bonn.de'
__version__ = 0.1
__data__ = '2008-04-15'
import numpy
import math
import random
#
# Sphere Point Picking algorithm, see
# http://mathworld.wolfram.com/SpherePointPicking.html
#
def rndSphere():
"""Generate a random point on a unit sphere, equally spaced on the
surface of the sphere. Returns cartesian coordinates of a vector.
"""
sph = [0,0,0]
sph[2] = random.uniform(-1.0,1.0)
z2 = math.sqrt(1.0 - sph[2]*sph[2])
phi = (2. * math.pi) * random.random()
sph[0] = z2 * math.cos(phi)
sph[1] = z2 * math.sin(phi)
return sph
def xrndSphere(n):
"""Generator, create n random points on a unit sphere. This is
very useful for looping:
for r in xrndSphere(10):
print r
"""
for i in xrange(n):
yield rndSphere()
def arndSphere(N):
"""Generate N random points on a unit sphere, equally spaced on the
surface of the sphere, and return them as columns of an array.
"""
sph = numpy.empty( (N,3), numpy.float )
sph[:,2] = numpy.random.uniform(-1.0,1.0,N) # z-coordinates
z2 = numpy.sqrt(1.0 - sph[:,2]**2)
phi = (2.0 * math.pi) * numpy.random.random( N )
sph[:,0] = z2 * numpy.cos(phi) # x
sph[:,1] = z2 * numpy.sin(phi) # y
return sph
