How to make random point/direction in spherical coordinate

If we want to pick a random point on the surface of a sphere, it is incorrect to select spherical coordinates \theta and \phi from uniform distributions 0 \leq \phi \leq 2\pi and 0 \leq \theta \leq \pi, since the area element \sin(\theta) d\theta d\phi is a function of \theta, and hence points picked in this way will be “bunched” near the poles (top).

To obtain points such that any small area on the sphere is expected to contain the same number of points, choose r_{1} and r_{2} to be random variates on (0,1). Then
\phi = 2 \pi r_{1}
\theta = arccos(1 - 2 r_{2} )
gives the spherical coordinates for a set of points which are uniformly distributed over S^{2} (bottom).

not uniform distribution

uniform distribution

// Copyleft (c) 2012. Ridlo W. Wibowo
using namespace std;

double unirand(){return (double) rand()/(double) RAND_MAX;}

int main(){
    double l = 0.1, phi, theta;
    double x, y, z;
    int n=10000;

    ofstream out("bola.txt");
    for (int i=0;i<n;i++){
        phi = 2.*M_PI*unirand();
        theta = acos(1. - 2.*unirand());
        //theta = M_PI*unirand();

        x = l*sin(theta)*cos(phi);
        y = l*sin(theta)*sin(phi);
        z = l*cos(theta);
        out << x << " " << y << " " << z << " " << endl;
    return 0;

Gnuplot script:

# gnuplot input file
set term wxt size 800,600
set parametric
set angle degree
set urange [0:360]
set vrange [-90:90]
set isosample 12,11
set ticslevel 0
#set xtics -0.06,0.02,0.06
#set ytics -0.06,0.02,0.06
set size 0.7,1.0
set nokey
splot a*fx(u,v),a*fy(u,v),a*fz(v), "bola.txt" w d lc 3
About these ads

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s