---
title: "testing variance computation with expected value and sigma"
output: html_notebook
---

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 \\
$$


```{r}
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)
c(sdR, sqrt(V), sqrt(V2))
```
```{r}
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")
```
```{r}
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
```
```{r}
plot(sigmaStar ~ cv, df[1:3,])
```

```{r}
sigmaStar <- 1.2
(cv <- sqrt(exp(log(sigmaStar)^2) - 1))
```

