Get random $x, y, z$ point inside a sphere?

485 Views Asked by At

What is the easiest way to get a random Point3D inside the sphere where is red?

diagram

3

There are 3 best solutions below

0
On BEST ANSWER

Use rejection sampling. Generate a candidate point in the sphere. If it so happens that the point is in the red region, accept it. If not then reject it and generate another candidate. After $n$ candidates are generated, roughly $np$ are accepted, where $p$ is the measure of the proportion of the sphere which is red.

0
On

This part of the shepre is isomorphic to $[a,b]\times [c,d]$ by the transformation $(sin(\theta)cos(\phi), sin(\theta)sin(\phi), cos(\theta)$ for $\phi \in [a,b], \theta \in [c,d]$.

So find the right $a,b,c,d$ by finding the range of the angles, random a number from $[a,b]\times [c,d]$ and use this transformation to get the coordinate on the shpere.

2
On

Say this is the sphere centered on the origin with radius 1, and your red area is that part of the sphere with $z > z_0$.

It turns out that if you generate a point $(u,v,z)$ uniformly at random on the cylinder with $u^2+v^2 = 1$ and $-1 \le z \le 1$ (the cylinder circumscribing the sphere) and then project it horizontally onto the sphere, taking

$$ \left( \sqrt{1-z^2} u, \sqrt{1-z^2} v, z \right) $$

then you have generated a point uniformly at random on the sphere. And of course you can generate $(u,v)$ as $(\cos \theta, \sin \theta)$ where $\theta$ is chosen uniformly at random in $(0, 2\pi)$.

If you restrict $z$ to be in $[z_0, 1]$, then this reduces to the case that you're talking about.

Therefore:

  • take $z$ uniformly at random in $[z_0, 1]$

  • take $\theta$ uniformly at random in $[0, 2\pi]$

  • return the point $\left( \sqrt{1-z^2} \sin \theta, \sqrt{1-z^2} \cos \theta, z \right)$.