0

When I ask Wolfram Alpha to calculate $E[f(X)]$ where $f(x) = e^{-x^2}$ and $X \sim \mathcal{N}(1,4)$, it gives the result $$ E[f(X)] = \frac{1}{3\sqrt[9]{e}} \approx 0.29828, $$ and the following plot which appears to be based on taking a number of simulations:

enter image description here

How can I generate the same type of plot using R?

Academic
  • 482
  • 3
  • 13
Bertus101
  • 123
  • 3

1 Answers1

3

You can simulate one of these lines like this:

library(ggplot2)
X<-rnorm(1000, 1, sqrt(4))
f<-function(x) exp(-x*x)
df<-data.frame(sample_size=seq_len(1000), sample_means=cumsum(f(X))/seq_len(1000))
ggplot(df, aes(x=sample_size, y=sample_means)) + 
geom_line() + theme_minimal() + labs(x=NULL, y=NULL)

enter image description here

Valentas
  • 1,064
  • 1
  • 8
  • 20