## Thursday, November 22, 2012

### Computing Expected Values

Original Code

# It is often times difficult to solve for the expected value of a variable in closed form.

# However, using computers it can be easy to approximate.

# Imagine (for whatever reason) you would like to calculate the expected value of exp(x) where x is distributed as a standard normal distribution.

# Method 1: Randomly draw many draws of the variable and take the mean.
draws = 100000
rvar = exp(rnorm(draws))
mean(rvar)

# Method 2: Draw from the inverse CDF
draws = 100000
CDF = seq(0.0000001,.9999999,length.out=draws)
rvar = exp(qnorm(CDF))
mean(rvar)

# Both methods are likely to produce very similar results.  Method 2 might be preferred because it is not susceptible to the random draw.  However, Method 1 has the strength of not having to specify and upper and lower limit to values entering the inverse CDF.

# Sometimes you might be interested in estimating the expected value of a censored variable.

# Say we are interested in exp(x) where x is still standard normal but missing at 0 and 2 (min = 0 and max = 2).

# This is easy to approximate as well.

draws = 100000
rvar = rnorm(draws)
rvar.cens = rvar[rvar > 0]
mean(rvar.cens)