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, , 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, 。
azimuth = 2*pi*rand(1000,1);
Create a radius value for each point in the sphere. These values are in the open interval, , 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
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.