four_lines - 2 years ago 114

Python Question

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

`a^2 + b^2 + c^2 = 1`

`a`

`b`

`sqrt(1 - a^2)`

`c`

`sqrt(1 - a^2 - b^2)`

Floating point values are fine, the sum of squares should be

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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**