Esercitazione4.R

lorenzo — Dec 2, 2013, 9:37 PM

# definisco la directory di lavoro
setwd("/Users/lorenzo/Documents/Lavori guidati e corsi matematica/ST410 a.a. 2013-2014/Esercitazione4")

#Es.1 
stim.media<-function(x,tipo) {if(tipo==1) a<-mean(x); if(tipo==2) a<-x[1]/2+x[length(x)]/2; if(tipo==3) a<-mean(x)-0.5; if(tipo==4) a<-sum(x*(0.5^(seq(1,length(x),1)))); if(tipo==5) a<-0;return(a)}
val.stim<-function(iter,n,mu,tipo) stim.media(rnorm(n,mu,1),tipo)
val.stim.vec<-Vectorize(val.stim,"iter")
vettore.stim<-function(iter,n,mu,tipo) val.stim.vec(1:iter,n,mu,tipo)

distorsione<-function(iter,n,mu,tipo) mu-mean(vettore.stim(iter,n,mu,tipo))
MSE<-function(iter,n,mu,tipo) mean((vettore.stim(iter,n,mu,tipo)-mu)^2)

distorsione.vec<-Vectorize(distorsione, "mu")
MSE.vec<-Vectorize(MSE,"mu")


#.1: curve della distorsione
#pdf(file="punto1.pdf", paper="a4r")
plot(NULL,xlim=c(-1,1),ylim=c(-0.6,0.6), main="Distorsione (n=2)", xlab="mu", ylab="distorsione")
abline(h=0,lty=1)
legend(-1,0.4,legend=paste(rep("T",5),1:5), col=rainbow(5), lty=1,ncol=2)
for(i in 1:5){curve(distorsione.vec(1000,2,x,i),from=-1, to=1, col=rainbow(5)[i], add=T,lwd=3)}

plot of chunk unnamed-chunk-1

#dev.off()


#.2: curve errore quadratico medio
#pdf(file="punto2.pdf", paper="a4r")
plot(NULL,xlim=c(-2,2),ylim=c(0,1.2), main="Errore quadratico medio (n=2)", xlab="mu", ylab="MSE")
legend(-0.5,1.2,legend=paste(rep("T",5),1:5), col=rainbow(5), lty=1,ncol=2)
for(i in 1:5){curve(MSE.vec(1000,2,x,i),from=-2, to=2, col=rainbow(5)[i], add=T, lwd=3)}

plot of chunk unnamed-chunk-1

#dev.off()


#.3: asintoticamente non distorto
#pdf(file="punto3.pdf", paper="a4r")
plot(NULL,xlim=c(-1,1),ylim=c(-0.6,0.6),main="Distorsione di T4 al variare di n", xlab="mu", ylab="distorsione")
abline(h=0,lty=1)
legend(-1,0.6,legend=paste(rep("n=",6),1:6), col=rainbow(6), lty=1,ncol=2)
for(i in 1:6){curve(distorsione.vec(1000,i,x,4),from=-1, to=1, col=rainbow(6)[i], add=T, lwd=3)}

plot of chunk unnamed-chunk-1

#dev.off()

#.4: consistenza in media quadratica
#pdf(file="punto4.pdf", paper="a4r")
plot(NULL,xlim=c(-2,2),ylim=c(0,1.2),  main="Errore quadratico medio di T1 al variare di n", xlab="mu", ylab="MSE")
legend(-2,0.9,legend=paste(rep("n=",10),1:10), col=rainbow(10), lty=1,ncol=2)
for(i in 1:10){curve(MSE.vec(1000,i,x,1),from=-2, to=2, col=rainbow(10)[i], add=T, lwd=3)}

plot of chunk unnamed-chunk-1

#dev.off()

#.5: non consistenza in media quadratica 
#pdf(file="punto5.pdf", paper="a4r")
plot(NULL,xlim=c(-2,2),ylim=c(0,1.2), main="Errore quadratico medio di T4 al variare di n", xlab="mu", ylab="MSE")
legend(-1,1.2,legend=paste(rep("n=",10),1:10), col=rainbow(10), lty=1,ncol=2)
for(i in 1:10){curve(MSE.vec(1000,i,x,4),from=-2, to=2, col=rainbow(10)[i], add=T, lwd=3)}

plot of chunk unnamed-chunk-1

#dev.off()