0

Given a point (p) and a Euclidean Distance (d), generate a random point (m) such that the Euclidean Distance between p and m is d.

This is easily to visualise and in 2D where the result set is just a circle of radius d around point p. However, the solution needs to work for any n-dimensional point (I am working with length 32 currently).

There is this StackOverflow thread for doing something similar for Cosine Similarity: Create random vector given cosine similarity

SimSimmer
  • 41
  • 1
  • 7

1 Answers1

0

For generating a random point (m) that is at a given distance (d) from a initial point (p) you can use the following:

M = P + v
where v = d*u
and u = (u1, u2, u3, ...) ; |u| = 1 --> |v| = d

(v and u are vectors of n-dimensional lenght, and |x| means the modulus of x)

So for generating a random point we only need to generate a random unit vector (u), from here we can get a simple code that generates a random unit vector. We only need to multiply the vector (be careful because is a list) with the distance, and add it to the point p.

Here is the final implementation (not fully compact for better comprehension):

from random import gauss


def make_rand_vector(dims):
    vec = [gauss(0, 1) for i in range(dims)]
    mag = sum(x**2 for x in vec) ** .5
    return [x/mag for x in vec]

def gen_random_point(p, d):
    u = make_rand_vector(len(p))  # generating a random unit vector
    v = [i*d for i in u]  # scaling the vector by d
    m = [i+k for i, k in zip(p, v)]  # adding the vector and the initial point
    return m

luisch444
  • 31
  • 5