Monte Carlo integration help needed I'm trying to simulate these two integrals using Monte Carlo simulation:
$$
\int_{-\infty}^\infty \exp(-x^2) dx, \quad \mbox{and } \int_{-\infty}^\infty \exp(-|x|) dx . 
$$
When I use runif(n,-Inf,Inf), I get NaN (number very close to zero) (using R).
I also tried converting that to a polar coordinates integral ($drdθ$ integral) but then I don't really know how to do the double integration needed.
Any ideas?
 A: According with runif manual page which you can find here, the min and max parameter values must be finite. If not it will produce NAs.
A: For suitably large $a>0$, you can sample from a $\mathrm{U}[-a,a]$ distribution because, for these two integrals, since the "tails" of the functions decay fast enough, $\int_{-\infty}^{-a} f(x)\,dx + \int_{a}^\infty f(x)\,dx$ is small. Don't forget to normalize the uniform density properly. For comparison, here are the analytical results and the corresponding simulations.
$$
  \int_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi} \approx 1.772454
$$
N <- 10^6
a <- 5
(2*a) * sum(exp(-(runif(N, -a, a)^2))) / N
[1] 1.77192

$$
  \int_{-\infty}^\infty e^{-|x|}\,dx = 2
$$
(2*a) * sum(exp(-abs(runif(N, -a, a)))) / N
[1] 1.988736

A: Uniform distribution is not defined on unbounded domain. It has to be $[-\infty<a<x<b<\infty]$.
That was your main issue. The second issue is that when you integrate with MC you don't have to use uniform distribution. Your case is a good example of when not to use it, in fact. Look up importance sampling subject in any Monte Carlo tutorial. Obviously, normal or exponential distributions would be good places to start for your integrals. 
In a nutshell, what you're doing is this: $\hat{I}=\sum_if(x_i)/p(x_i)$, where $p(x_i)$ is the  PDF of your sampling distribution. In the most basic case it would uniform distribution, i.e. $\frac{1}{b-a}$. If you use normal distribution it'll be $\frac{e^{-x_i^2/2}}{\sqrt{2\pi}}$.
UPDATE:
The MATLAB code would be like this: 
x=randn(10000,1);
mean(exp(-x.^2)./normpdf(x))

ans =

    1.7828

