Earlier today I needed to solve for log normal parameters that yield a given mean and variance. I’m going to save the calculation here in case I needed in the future or in case a reader needs it. The derivation is simple, but in the heat of the moment I’d rather look it up and keep going with my train of thought.
NB: The parameters μ and σ² of a log normal distribution are not the mean and variance of the distribution; they are the mean and variance of its log.
If m is the mean and v is the variance then
Notice that the square of the m term matches the second part of the v term.
and once you have σ² you can find μ by
Here’s Python code to implement the above.
from numpy immport log def solve_for_log_normal_parameters(mean, variance): sigma2 = log(variance/mean**2 + 1) mu = log(mean) - sigma2/2 return (mu, sigma2)
And here’s a little test code for the code above.
mean = 3.4 variance = 5.6 mu, sigma2 = solve_for_log_normal_parameters(mean, variance) X = lognorm(scale=exp(mu), s=sigma2**0.5) assert(abs(mean - X.mean()) < 1e-10) assert(abs(variance - X.var()) < 1e-10)