Main Content

Random Numbers Within a Sphere

This example shows how to create random points within the volume of a sphere, as described by Knuth[1]。The sphere in this example is centered at the origin and has a radius of 3.

One way to create points inside a sphere is to specify them in spherical coordinates. Then you can convert them to Cartesian coordinates to plot them.

First, initialize the random number generator to make the results in this example repeatable.

rng(0,'twister')

Calculate an elevation angle for each point in the sphere. These values are in the open interval, ( - π / 2 , π / 2 ) , but are not uniformly distributed.

rvals = 2*rand(1000,1)-1; elevation = asin(rvals);

Create an azimuth angle for each point in the sphere. These values are uniformly distributed in the open interval, ( 0 , 2 π )

azimuth = 2*pi*rand(1000,1);

Create a radius value for each point in the sphere. These values are in the open interval, ( 0 , 3 ) , but are not uniformly distributed.

radii = 3*(rand(1000,1).^(1/3));

Convert to Cartesian coordinates and plot the result.

[x,y,z] = sph2cart(azimuth,elevation,radii); figure plot3(x,y,z,'.') axisequal

Figure contains an axes object. The axes object contains an object of type line.

If you want to place random numberson the surfaceof the sphere, then specify a constant radius value to be the last input argument tosph2cart。In this case, the value is3

[x,y,z] = sph2cart(azimuth,elevation,3);

References

[1] Knuth, D.The Art of Computer Programming。2卷,第3版。阅读,MA: addison - wesley长man, 1998, pp. 134–136.

See Also

||

Related Topics