Search code examples
anylogicprobability-density

AnyLogic: Definition of Lognormal-Distribution directly via its mean and standard deviation


I tried to model a lognormal distribution in AnyLogic and I have its standard deviation and its mean but NOT the standard deviation and mean of its included normal distribution (as AnyLogic demands). How can I model a lognormal distribution directly via ITS mean and standard deviation?

I tried to take the logarithm of my mean to implement it b/o this formula:

E(X) = exp[my+(sigma^2)/2]. So when I take the logarithm, I should get my+(sigma^2)/2. When sigma=0, I could implement a lognormal distribution, but when sigma exists, above formula also depens on sigma. Therefore, I do not know how I could implement a lognormal distribution directly over ITS mean, sigma and minimum value = 0 in AnyLogic.

Does anyone have a solution to this?


Solution

  • What you need to do is calculate the correct parameters for the included normal distribution based on what you want the mean and variance of your lognormal to be. I went through these calculations and made some AnyLogic code to show how to do it. In my code, targetMean := "The desired mean of the lognormal distribution." And targetVariance := "The desired variance of the lognormal distribution."

    To calculate the parameters of the included normal distribution, the first function is

    getMu(targetMean, targetVariance):

    double mu = log(targetMean) - getSigma2(targetMean,targetVariance)/2.0;
    
    return mu;
    

    The second function is

    getSigma2(targetMean,targetVariance):

    double sigma2 = log(targetVariance/pow(targetMean,2) + 1);
    
    return sigma2;
    

    Here is an article going through the calculations: https://www.johndcook.com/blog/2022/02/24/find-log-normal-parameters/

    and here is the result:

    double targetMean = 8.0;
    double targetVariance = 3.0;
    for(int i=0;i<5000;i++)
    {
        lognormalSamples.add(lognormal(getMu(targetMean,targetVariance),sqrt(getSigma2(targetMean,targetVariance)), 0));
    }
    
    traceln("Realized mean = " + lognormalSamples.mean());
    traceln("Realized var = " + lognormalSamples.variance());
    

    Don't forget to sqrt sigma2 in the input to lognormal. This gives the correct mean and variance that I specified for the lognormal:

    Realized mean = 7.991504691617353
    Realized var = 2.9660508827785415