# How to generate random numbers from a log-normal distribution in python ?

Daidalos May 09, 2020

Example of how to generate random numbers from a log-normal distribution in python ?

Log-normal distribution:

\frac{1}{x \sigma \sqrt{2\pi}}.exp(-\frac{(len(x)-\mu)^2}{2\sigma^2})

### 2 -- Using scipy lognorm

Example of how to generate random numbers from a log-normal distribution with $\mu=0$ and $\sigma=0.5$ using scipty function lognorm:

from scipy.stats import lognorm

import numpy as np
import matplotlib.pyplot as plt

std = 0.5

print(lognorm.rvs(std))

data = lognorm.rvs(std, size=100000)

#print(data)

hx, hy, _ = plt.hist(data, bins=50, normed=1,color="lightblue")

plt.ylim(0.0,max(hx)+0.05)
plt.title('Generate random numbers \n from a log normal distribution with python')
plt.grid()

plt.savefig("generate_random_numbers_log_normal_distribution_01.png", bbox_inches='tight')
#plt.show()
plt.close()

print(np.mean(data))
print(np.exp(std**2 / 2.0))

print(np.std(data))
var = (np.exp(std**2)-1)*np.exp(std**2)
print( np.sqrt(var) )


Note: if $\mu \ne 0$ just multiply by $exp(\mu)$, example:

mu = 3.0
std = 0.5

data = lognorm.rvs(std, size=100000) * np.exp(mu)

hx, hy, _ = plt.hist(data, bins=50, normed=1,color="lightblue")

plt.ylim(0.0,max(hx)+0.05)
plt.title('Generate random numbers \n from a log normal distribution with python')
plt.grid()

plt.savefig("generate_random_numbers_log_normal_distribution_02.png", bbox_inches='tight')
plt.show()

plt.close()

print(np.mean(data))
print(np.exp(mu + std**2 / 2.0))

print(np.std(data))

var = (np.exp(std**2)-1)*np.exp(2*mu+std**2)
print( np.sqrt(var) )


### 2 -- Using a normal distribution with numpy: random.randn()

Another solution is to use random.randn():

exp(\mu + \sigma Z)

mu = 3.0
sigma = 0.5

data = np.random.randn(100000) * sigma + mu
data = np.exp(data)

hx, hy, _ = plt.hist(data, bins=50, normed=1,color="lightblue")

plt.ylim(0.0,max(hx)+0.05)
plt.title('Generate random numbers \n from a log normal distribution with python')
plt.grid()

#plt.savefig("generate_random_numbers_log_normal_distribution_02.png", bbox_inches='tight')
plt.show()