Solution (source code)

= Solution

A weighting function must first be normalized to a <probability density>. The constant choice on $[a,b]$ means
$$
q(x)=\frac1{b-a},\qquad
I=\mathbb E_q\left[\frac{f(X)}{q(X)}\right]=(b-a)\mathbb E_q[f(X)].
$$
Equivalently, transform $x=a+(b-a)z$ and use the already normalized $g(z)=1$ on $[0,1]$. Independent samples give the unbiased <Monte Carlo integration> estimator
$$
\boxed{\widehat I_N=\frac{b-a}{N}\sum_{j=1}^N f(a+(b-a)U_j),\quad U_j\sim\mathrm{Uniform}(0,1).}
$$

``
function uniform_monte_carlo(f, a, b, N):
    require N >= 2
    total = 0
    total_squared = 0
    for j in 1,...,N:
        u = independent_uniform_0_1()
        value = f(a+(b-a)*u)
        total += value
        total_squared += value*value
    average = total/N
    sample_variance = (total_squared-N*average*average)/(N-1)
    integral = (b-a)*average
    standard_error = abs(b-a)*sqrt(sample_variance/N)
    return integral, standard_error
``

For a general positive normalized importance density $q$, replace each sample contribution by $f(X_j)/q(X_j)$ with $X_j\sim q$. Here the uniform choice is the special case of <importance sampling> that assigns equal weight to every region of equal length.