YBerman YBerman - 6 months ago 21
Python Question

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()
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
takes very long for even small n like 17. Is there a better (faster) way to get a random point on an n-sphere?


According to Muller, M. E. "A Note on a Method for Generating Points Uniformly on N-Dimensional Spheres" you would need to create a vector of n gaussian random variables and divide by its length:

import random
import math

def randnsphere(n):
  v = [random.gauss(0, 1) for i in range(0, n)]
  inv_len = 1.0 / math.sqrt(sum(coord * coord for coord in v))
  return [coord * inv_len for coord in v]

As stated by @Bakuriu in the comments, using numpy.random can offer you a performance advantage when working with larger vectors.