I am trying to make a random number generator that I could change the distribution based on its PDF, I know they are different random number generator in libraries available but I want to write a function that is customized, in the following, I tried to make this function for normal distribution. (again, I am not looking for a normal random generator, I am trying to make this one work so I could change the PDF and other parameter later on)
I know that this is the dumb way to write this. Because of too many loops it is not efficient at all but it is working and I could get pretty close means from the generated data.
What is the best way to improve this function?
import numpy as np
import math as ms
def gen_gaussian(mu = 0, sigma = 1, n = 1):
u = np.random.uniform(0, 1, n)
def norm_pdf(x, m, s):
result = []
for i in range(len(range_x)):
result.append(((1/ms.sqrt(2*ms.pi*(m**2)))*(ms.exp(-((x[i]-m)**2)/(2*(s**2))))))
return result
bound_l = mu - 200*sigma
bound_u = mu + 200*sigma
range_x = np.arange(bound_l, bound_u, sigma/1000)
cdf_values = np.cumsum(norm_pdf(range_x, mu, sigma))*sigma/1000
output = []
index_list = []
index_num = None
#min_v = cdf_values[0] - u[0]
for i in range(n):
index_list.append(index_num)
min_v = cdf_values[0] - u[i]
for j in range(cdf_values.shape[0]):
if ((cdf_values[j] - u[i]) < min_v):
index_num = j
for i in range(len(index_list)):
output.append(range_x[index_list[i]])
return np.array(output).mean()
gen_gaussian(2, 1, 10)
Aucun commentaire:
Enregistrer un commentaire