[SciPy-User] random points within an ellipse
Erin Sheldon
erin.sheldon@gmail....
Thu Aug 5 11:32:20 CDT 2010
Excerpts from Benjamin Root's message of Wed Aug 04 19:38:51 -0400 2010:
> Hi,
>
> For a project, I need to create sets of random coordinates within a 2d
> domain. To start, I have been creating random x and y coordinates, which
> has worked very nicely. However, I would like to start doing some fancier
> domains like ellipses and crescents. Does anybody know of any useful tricks
> for doing this?
>
> Thanks,
> Ben Root
Hi Ben -
A simple way is to generate random x and y coordinates in a bounding box
and then trim back to the shape you want using your constraint. E.g.
for an ellipse:
# equation of ellipse:
# (x/x0)^2 + (y/y0)^2 = 1
# or
x=2*x0*(random.random(n-nkeep) - 0.5)
y=2*y0*(random.random(n-nkeep) - 0.5)
# get points that fall within constraint
w,=where( ( (x/x0)**2 + (y/y0)**2 ) < 1 )
You can put this in a while loop to get the desired number:
import numpy
from numpy import random, where, cos, sin, arctan2, abs
def get_random_ellipse(n, x0, y0):
xout = numpy.zeros(n)
yout = numpy.zeros(n)
nkeep=0
while nkeep < n:
x=2*x0*(random.random(n-nkeep) - 0.5)
y=2*y0*(random.random(n-nkeep) - 0.5)
w,=where( ( (x/x0)**2 + (y/y0)**2 ) < 1 )
if w.size > 0:
xout[nkeep:nkeep+w.size] = x[w]
yout[nkeep:nkeep+w.size] = y[w]
nkeep += w.size
return xout,yout
More information about the SciPy-User
mailing list