vendredi 8 juillet 2016

Computationally picking a random point on a n-sphere


I need to randomly pick an n-dimensional vector with length 1. My best idea is to pick a random point in the sphere an normalize it:

import random

def point(n):
    sq = 0
    v = []
    while len(v) < n:
        x = 1 - 2*random.random()
        v.append(x)
        sq = sq + x*x
        if sq > 1:
            sq = 0
            v = []
    l = sq**(0.5)
    return [x / l for x in v]

The only problem is the volume of an n-ball gets smaller as the dimension goes up, so using a uniform distribution from random.random takes very long for even small n like 17. Is there a better (faster) way to get a random point on an n-sphere?


Aucun commentaire:

Enregistrer un commentaire