How to generate uniform random points inside d-dimension ball / sphere?
In this thread, @Thomas Lux has a wonderful solution of generating uniformly random points inside an nD ball with radius r=1. But now I want to generate points where their Cartesian coordinates are integers. I do not know any way except generating random points in a cube and throwing out the points with norm greater than 1.
I don't know if simply using randint
or pushing np.floor()
to the vector will do.
Simply using round()
on uniform real samples would almost work. Except the integer points near the edge of the ball would have lower probabilities of showing up. That's because the hypercube-neighborhood of a point on the edge is less than half-contained in the ball you're sampling from.
There is an easy workaround though. Generate real samples in a ball that fully contains all such hypercubes, the radius r+sqrt(n)/2
should be enough for that, then apply rounding, and finally discard the integer points that are not within distance r
.
Certainly the outer ball can be much larger than the inner one, depending on r
and n
, but the discard rate should still be better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With