four_lines four_lines - 2 years ago 114
Python Question

Generating random numbers a, b, c such that a^2 + b^2 + c^2 = 1

To do some simulations in Python, I'm trying to generate numbers a,b,c such that

a^2 + b^2 + c^2 = 1
. I think generating some
between 0 and 1, then some
between 0 and
sqrt(1 - a^2)
, and then
sqrt(1 - a^2 - b^2)
would work.

Floating point values are fine, the sum of squares should be close to 1. I want to keep generating them for some iterations.

Being new to Python, I'm not really sure how to do this.

Answer Source

The "right" answer depends on whether you are looking for a uniform random distribution in space, or on the surface of a sphere, or something else. If you are looking for points on the surface of a sphere, you still have to worry about the cos(theta) factor which will cause points to appear "bunched up" near the poles of the sphere. Since exact nature is not clear from your question, here is a "totally random" distribution that should work:

x = np.random.uniform(0,1,3) # random numbers in [0, 1)
x /= np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2)

Another advantage here is that since we are using numpy arrays, you can quickly scale to large sets of points too, by using x = np.random.uniform(0, 1, (3, n)) for any n.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download