均匀球形分布的随机三维单位向量

生成具有均匀球形分布的随机三维单位向量[参考]

import numpy as np
import matplotlib.pyplot as plt
def random_three_vector():
    """
    Generates a random 3D unit vector (direction) with a uniform spherical distribution
    Algo from http://stackoverflow.com/questions/5408276/python-uniform-spherical-distribution
    :return:
    """
    phi = np.random.uniform(0,np.pi*2)
    costheta = np.random.uniform(-1,1)

    theta = np.arccos( costheta )
    x = np.sin( theta) * np.cos( phi )
    y = np.sin( theta) * np.sin( phi )
    z = np.cos( theta )
    return (x,y,z)

# Example IPython code to test the uniformity of the distribution
from pylab import scatter
threetups = []
for _ in range(1000):
    threetups.append(random_three_vector())
x,y,z = zip(*threetups)

plt.scatter(x, y)
plt.title("Distribution of Random 3D Unit Vectors")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

result:

均匀球形分布的随机三维单位向量_第1张图片

你可能感兴趣的:(算法)