beta=5
n=1000

ff<-function(t)
{
	if (t>0)
	{
		z=exp(beta*t)
	}
	else
	{
		z=0
	}
	return(z)
}

gg<-function(t)
{
	u=exp(-t*t/2)/sqrt(2*pi)
	v=exp(-(t-beta)^2/2)/sqrt(2*pi)
	return(ff(t)*u/v)	
}

#Question 1
#Calcul de la variance de la méthode naïve.
s=0
for (i in 1:n)
{
	u=rnorm(2,0,1)
	s=s+(ff(u[1])-ff(u[2]))^2
}
s=s/(2*n)
cat("Variance naïve : ",s,"\n")

#Question 2
#Échantillonage d'importance
s=0
for (i in 1:n)
{
	u=rnorm(2,beta,1)
	a=gg(u[1])
	b=gg(u[2])
	s=s+(a-b)^2	
	print(a-b)
}
s=s/(2*n)
cat("Variance 1 : ",s,"\n")
	
#Question 3
#Variable de contrôle
h<-function(t)
{
	return(exp(beta*t))	
}	
	
s=0
for (i in 1:n)
{
	u=rnorm(2,0,1)
	a=ff(u[1])-h(u[1])
	b=ff(u[2])-h(u[2])
	s=s+(a-b)^2
}
s=s/(2*n)
cat("Variance 2 : ",s,"\n")

#Question 4
#Variables antithétiques 
#On remarque que X et -X ont même loi.
s=0
for (i in 1:n)
{
	u=rnorm(2,0,1)
	a=(ff(u[1])-h(u[1])+ff(-u[1])-h(-u[1]))/2
	b=(ff(u[2])-h(u[2])+ff(-u[2])-h(-u[2]))/2	
	s=s+(a-b)^2
}
s=s/(2*n)
cat("Variance 3 : ",s,"\n")