Rachel_1988 - 9 months ago 55

PHP Question

I figured I'd use rand() to get a number between 0 and 20000 twice to get a random x and y coordinate. This works but it gives me random coordinates from within a square.

What I really need is coordinates within a circle. How can I limit my random x/y to within a circle which has a radius of 20,000?

I've tried a few sample codes online but most of those seem to be for computing spheres and finding the distance between two points on a sphere and I'm not knowledgeable enough to apply those to my usage of just picking a random coordinate within a circle (flat) radius.

Any help would be greatly appreciated.

Answer

You can get a random `x`

between -20,000 and 20,000 and use Pythagoras law to get the positive `y`

value. Then you do a random 0 or 1 to make that value positive or negative.

An example:

```
$r = 20000;
$x = rand(-$r, $r);
$y = rand(0, 1) ? -sqrt(pow($r, 2) - pow($x, 2)) : sqrt(pow($r, 2) - pow($x, 2));
var_dump($x, $y);
```

I am not sure how the numbers are distributed exactly but it sounds about right.