# testing variance computation with expected value and sigma

Formula for Variance given sigma at log scale and expected value

We start with formulas for variance and mean. \[ V = (e^{\sigma^2} - 1) e^{2\mu + \sigma^2} \\ m = e^{\mu + \sigma^2/2} \] mean formula resolved for \(\mu\) and substituted into V. \[ \mu = log_m - \sigma^2/2 \\ V = (e^{\sigma^2} - 1) e^{2(log_m - \sigma^2/2) + \sigma^2} \\ V = (e^{\sigma^2} - 1) e^{2log_m - \sigma^2 + \sigma^2} \\ V = (e^{\sigma^2} - 1) e^{2log_m} \\ V = (e^{\sigma^2} - 1) (e^{log_m})^2 \\ V = (e^{\sigma^2} - 1) m^2 \\ \]

    n = 1e4
    sigma = log(1.2)
    #sigma = log(1.41)
    mu = log(10)
    logR = rnorm(n, mu, sigma)
    R = exp(logR)
    meanR = mean(R)
    sdR = sd(R)
    V2 = (exp(sigma^2) - 1)*exp(2*mu + sigma^2)
    #
    m = exp(mu + sigma^2/2)
    V = (exp(sigma^2) - 1)*m^2
    c(meanR, m)

    [1] 10.19334 10.16759

    c(sdR, sqrt(V), sqrt(V2))

    [1] 1.883301 1.869284 1.869284

    xPred <- seq(-2,22,length.out = 101)
    plot(density(R), xlim = c(-2,22), lty = "dotted")
    abline(v = meanR)

    lines(dnorm(xPred, m, sqrt(V))~xPred, col = "blue", lty = "dashed")
    lines(dlnorm(xPred, mu, sigma)~xPred, col = "green")

    df <- data.frame(cv = c(0.05,0.1,0.2,0.5,1,2,5,10,20))
    df$sigma = sqrt(log(df$cv^2 + 1))
    df$sigmaStar <- exp(df$sigma)
    #df$cvRev <- sqrt(exp(log(df$sigmaStar)^2) - 1)
    df

    plot(sigmaStar ~ cv, df[1:3,])

    sigmaStar <- 1.2
    (cv <- sqrt(exp(log(sigmaStar)^2) - 1))

    [1] 0.1838472

LS0tCnRpdGxlOiAidGVzdGluZyB2YXJpYW5jZSBjb21wdXRhdGlvbiB3aXRoIGV4cGVjdGVkIHZhbHVlIGFuZCBzaWdtYSIKb3V0cHV0OiBodG1sX25vdGVib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