【问题标题】:Generate uniformly distributed points in a circle在圆内生成均匀分布的点
【发布时间】:2020-09-14 17:09:08
【问题描述】:

''' 我试图在一个应该均匀分布的圆圈中生成点,但我得到了一个奇怪的模式。如果我将半径 R 增加到一个非常大的值,则分布看起来是正常的,但 R 值较小时会产生螺旋。有什么改进代码的建议吗? '''

from numpy.random import uniform
#from scipy.stats import uniform
import matplotlib.pyplot as plt
import numpy as np
import math  

R = 5
# Generate uniformly distributed random numbers.
rand_num = []
for i in range(30000):
    rand_num.append(np.random.uniform(0,1))

# Use these generated numbers to obtain the CDF of the radius which is the true radius i.e. r = R*sqrt(random()).
radius = []
for n,data in enumerate(rand_num):
    radius.append(R*math.sqrt(data))

# Generate the angle using the same uniformly distributed random numbers.
theta2 = []
for n, k in enumerate(radius):
    theta2.append(2*math.pi*radius[n])

# Calculate the corresponding x-coordinate.
x = []
for j,v in enumerate(radius):
    x.append(radius[j]*math.cos(theta2[j]))
x = np.array(x)   

# Calculate the correspoding y-coordinate.
y = []    
for j,v in enumerate(radius):
    y.append(radius[j]*math.sin(theta2[j]))
y = np.array(y)

# Finally plot the coordinates.
plt.figure(figsize=(10,10))
plt.scatter(x, y, marker='o')

【问题讨论】:

    标签: python numpy random uniform-distribution


    【解决方案1】:

    是的,因为theta 和radius 都与rand_num 成正比,所以代码应该会给你一个螺旋。相反,您应该独立生成theta 和radius。另外,使用 numpy 的矢量化运算符而不是数学的

    R = 5
    num_points = 10000
    
    np.random.seed(1)
    theta = np.random.uniform(0,2*np.pi, num_points)
    radius = np.random.uniform(0,R, num_points) ** 0.5
    
    x = radius * np.cos(theta)
    y = radius * np.sin(theta)
    
    # visualize the points:
    plt.scatter(x,y, s=1)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      相关资源
      最近更新 更多