Reputation: 19
I have set of points defined by inequalities
f.e 0<x<3
, 0<y<3
and x^2+y^2>1
,
How can I randomly choose a point from this set?
Upvotes: 0
Views: 173
Reputation: 69869
You can use rejection sampling, e.g.:
function myrand(R)
while true
x, y = 3rand(), 3rand() # now x∈[0,3[ and y∈[0,3[
x^2+y^2>R^2 && return (x,y)
end
end
Of course you should make sure that R^2<18
as otherwise you will get an infinite loop. The function is more expensive (takes more time to finish) the closer R
is to this boundary.
If you wanted to improve the speed of it and R>3
(e.g. when you are very close to the boundary) then you can sample x
and y
from the interval [sqrt(R^2-9),3]
by rescaling rand()
result appropriately. The reason is that you know that if x
or y
is less or equal than sqrt(R^2-9)
you will reject such a sample for sure (effectively you sample from a smaller square).
Upvotes: 2