Accelerating the pace of engineering and science

# Documentation Center

• Trials

## 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.

Convert to Cartesian coordinates and plot the result.