I am doing simulation that I want a point םמ a sphere to be picked at random. I used spherical coordinates, to uniformly generate $\theta$ ,$\phi$, but I found it that it does not really uniformly generates the values along x,y,z. x and y histogram peaked at 0, while z histogram peaked at r. Is there a way to make it more random?
generate 3 random variables uniformly that correspond to a hyper plane.
77 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail AtThere are 2 best solutions below
On
From the rest of the question, I gather that you're using "within a sphere" in the precise technical sense in which it's synonymous with "on a sphere".
The uniform distribution over a sphere is uniform in $z$ (equivalently in $\cos\theta$), so you can choose $z$ uniformly from $[-1,1]$ and $\phi$ uniformly from $[0,2\pi]$ and use
$$ x=\sqrt{1-z^2}\cos\phi\;,\\ y=\sqrt{1-z^2}\sin\phi\;,\\ z=z\;. $$
Then by symmetry $x$ and $y$ will also be uniform over $[-1,1]$.
Alternatively, you can draw three coordinates from the normal distribution and normalise them; or you can draw three coordinates in the cube $[-1,1]^3$, reject them if they're outside the unit sphere and otherwise normalise them. That last variant requires the fewest non-elementary operations, just one square root for the normalisation (since the distance from the origin can be checked without drawing the root).
Why does your title say "hyper plane" but your question talks about spheres?
If you want point on the sphere, read this.
If you want points within the sphere, a simple solution is to generate $x$, $y$, and $z$ uniformly in $[-r,r]$ and simply reject all points that are outside $x^2+y^2+z^2>r^2$. Also see this related (identical?) question.