Normal-distributed Random Generator

De Augusto Baffa Wiki
Ir para navegação Ir para pesquisar
Esta página é uma versão traduzida da página Gerador Aleatório para Distribuição Normal. Sua tradução está 100% completa.
Outros idiomas:
English • ‎português do Brasil

Normal or Gaussian distribution is, without any doubt, the most famous statistical distribution (primarily because of its link with the Central Limit Theorem).

It turns out that using a special method called Box-Muller transform, we can generate Normally distributed random variates from Uniform random generators.


[math]Z0 = \sqrt{-2ln(U_1)}.cos(2\pi U_2)[/math]


[math]Z1 = \sqrt{-2ln(U_1)}.sin(2\pi U_2)[/math]


The Box-Muller Sampling for a Normal Distribution is [math]\mathcal {N}(\mu, \sigma) = z \times \sigma + \mu[/math], where [math]z = Z_0 \text{ or } Z_1[/math].

Sample Python Code

1 million attempts sample
def pseudo_normal(mu=0.0, sigma=1.0, size=1):
    """
    Generates normal distribution from uniform generator
       using Box-Muller transform
    """
    # Sets seed based on the decimal portion of the current system clock
    t = time.perf_counter()
    seed1 = int(10**9*float(str(t-int(t))[0:]))
    U1 = pseudo_uniform(seed=seed1, size=size)
    
    t = time.perf_counter()
    seed2 = int(10**9*float(str(t-int(t))[0:]))
    U2 = pseudo_uniform(seed=seed2, size=size)
    
    # Standard Normal pair
    Z0 = np.sqrt(-2*np.log(U1)) * np.cos(2*np.pi*U2)
    Z1 = np.sqrt(-2*np.log(U1)) * np.sin(2*np.pi*U2)    
    
    # Scaling
    Z0 = Z0 * sigma + mu
    
    return Z0