Simular uma função que gera amostras semi-normais por meio do algoritmo visto em sala, utilizando o método da aceitação-rejeição e plotar o gráfico.
rsemi_gauss <- function(n=1){
k <-0
result<-data.frame(z=numeric(),u=numeric(), gz=numeric(), I=numeric() )
while (k<n) {
z <- rexp(1)
result1<-data.frame(z=z, u=runif(1), gz=exp(-(z-1)^2/2),I=0)
if (result1$u<=result1$gz)
{result1$I<-1
k <- k+1
}
else{
result1$I<-0
k<-k
}
result<-rbind(result,result1)
}
return(result)
}
# Testando a função
a <- rsemi_gauss(1000)
# Histograma da função
hist(a$z, main = "Histograma Semi-Normal", col = "pink")
library(RColorBrewer)
c <- sqrt(2*exp(1)/pi)
x <- seq(0, 6, length=1000)
# h(x): semi-normal positiva
hx <- sqrt(2/pi)*exp((-x^2)/2)
cx <- c*dexp(x)
par(las=1, mar=c(4, 4, 2, 2))
plot.new()
plot.window(range(x), c(0,c*dexp(0)))
axis(1, cex=.5)
axis(2, cex=.5)
mtext("Densidade", side=2, line=3, las=0, cex=1)
lines(x,hx, col="black", type="l",lwd=1.75,ylab="Densidade",cex=.5)
lines(x,cx, col="darkblue", type="l",lwd=1.75)
u <- a$u
g <- a$z
fig <-which(g<6)
u <- u[fig]
g <- g[fig]
hg <- (c*dexp(g))
cores <- brewer.pal(3,"Reds")
classes <- (u<=sqrt(2/pi)*exp((-g^2)/2)/hg)*1 + 2
points(g,u*hg,col=cores[classes],pch=19,cex=.75)