Skip to content
Advertisement

How to chose a random point at a certain distance to a reference point

I have point A (pointA = (x1, y1)) and I need to choose a random point B (pointB = (x2, y2)) such that the distance between the A and B is equal to K.

Advertisement

Answer

Let’s solve in polar form.

We’ll need these doubles distance, x1, and y1.

First, we want the angle in radians:

double angle = Math.random()*2*Math.PI;

Then we want to get the x and y offsets from our point:

double xOff = Math.cos(angle)*distance;
double yOff = Math.sin(angle)*distance;

Then we add these to our first point:

double x2 = x1 + xOff;
double y2 = y1 + yOff;

This will get you a point a certain distance away from your first point.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement