Numpy, the given norm returns the possible Cartesian coordinates

Is there some simple tool in numpy that sets an x ​​value, returns three random coordinates whose modulus is x?

+3


source to share


2 answers


Well, I don't think you will find anything in numpy for this purpose, but it will be pretty fast:

from numpy.random import normal
from numpy.linalg import norm
from numpy import allclose
def random_vec(modulus):
    while True:
        y = normal(size=(3,))
        if not allclose(y,0):
            y *= modulus / norm(y)
            return y

      

Above I am assuming that with the modulus of the vector you mean the L2 norm . Note that we have to check that at least one coordinate is not too close to zero (or zero!), So we have no problems with numerical rounding when rescaling the components.



EDIT: instead of rand()

now use normal()

The reason why we choose coordinates from a normal distribution (and then, of course, scaling them) to get a random point on a sphere of radius modulus

is explained here . Read also unutbu's comments below.

+2


source


Assuming you want 3-dimensional Cartesian coordinates (X,Y,Z)

, you can do so with two random angle selections in spherical polar coordinates and then convert back to Cartesian:

import numpy as np

# Example data: three values of x = sqrt(X^2 + Y^2 + Z^2)
x = np.array([1, 2, 2.5])

n = len(x)
theta = np.arccos(2 * np.random.random(n) - 1)
phi = np.random.random(n) * 2. * np.pi

X = x * np.sin(theta) * np.cos(phi)
Y = x * np.sin(theta) * np.sin(phi)
Z = x * np.cos(theta)

      



gives (for example):

[-2.60520852  0.01145881  1.01482376]
[-0.85300437  0.29508229 -1.54315779]
[ 1.21871742 -0.95540313  3.54806944]

      

0


source







All Articles