mercredi 27 mai 2020

Generate uniformly distributed points in a circle

''' I am trying to generate points in a circle that should be uniformly distributed but I get a weird pattern. If I increase the radius R to a very large value, the distribution appears normal but with smaller R values it generates spirals. Any suggestions to improve the code? '''

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')



Aucun commentaire:

Enregistrer un commentaire