import numpy as np
\[ I(p)=\int_{0}^{\pi}cos(px)sin(x)dx = \frac{1+cos(\pi p)}{1 - p^2} \]
\[ I(p) \approx \frac{\pi^2 q}{4}\left(\frac{q}{2} - 1\right) , \; q = p - 1\]
error: \[ \epsilon = \frac{\pi^2 q^3}{16}\left(\frac{\pi^2}{3} - 1\right) \approx 1.412505788140299 \; q^3 \]
\[ \frac {\pi^2} {4} = 2.467401100272340 \]
def int_cs(p):
''' exact integral (for comparison) '''
q = p - 1
Pi = math.pi
if (abs(q) > 0.001):
return (1+cos(Pi*p))/(1-p*p)
else:
return 2.4674011*q*(0.5*q - 1)
Make int_cs work on vectors
vint_cs = np.vectorize(int_cs)
pp = np.linspace(0.0,3.0,151)
Exact integral generation
jj = vint_cs(pp)
plot(pp,jj)
title('Exact integral')
xlabel('$p$')
ylabel('$I(p)$')
Monte Carlo integration \[ I(p)=\int_{a}^{b}f(x; p)dx \approx \frac{1}{N}\sum_{i=1}^{N}f(x_{i}; p) \]
def MC(p, f, a, b, n, reset = False):
s = 0.0
if reset:
np.random.seed(1)
x = np.random.uniform(a, b, n)
y = f(x, p)
return np.average(y)*(b-a)
def cs(x, p):
return cos(p*x)*sin(x)
Test
I = MC(0.0, cs, 0.0, math.pi, 1000)
print("I(0) = ", I, " - expected 2")
Generate \(I(p)\) without seed reset
def IMC(p, reset=False):
return MC(p, cs, 0.0, math.pi, 500, reset)
vIMC = np.vectorize(IMC)
ii = vIMC(pp)
plot(pp,jj, 'r', label=r'$ I(p) $')
plot(pp,ii, label=r'$ I_{MC}(p) $')
title('Monte Carlo without seed reset')
legend();
xlabel('$p$')
#ylabel('Imc(p), I(p)')
Generate \(I(p)\) with seed reset
kk = vIMC(pp, True)
plot(pp,jj,'r', label=r'$ I(p) $')
plot(pp,kk, label=r'$ I_{MC}^{(r)}(p) $')
title('Monte Carlo with seed reset')
legend();
xlabel('$p$')
#ylabel('Imc(p, reset=True), I(p)')
Monte Carlo error \(I_{MC}(p) - I(p)\)
plot(pp,ii-jj)
title('Monte Carlo error')
ylabel('$I_{MC}(p) - I(p)$')
xlabel('$p$')
Error for Monte Carlo with seed reset: \(I_{MC}^{(r)}(p) - I(p)\)
plot(pp,kk-jj)
title('Error for Monte Carlo with seed reset')
xlabel('$p$')
ylabel('$I_{MC}^{(r)}(p) - I(p)$')
e = ii-jj
eMC = e.std()
print(eMC)