###
### univariate density estimation
###
f0 <- function(x) 1.5*(x>=0)-(x>=.25)+(x>=.75)-1.5*(x>1)
set.seed(1)
m <- 1000
x1 <- runif(m)
ind <- (runif(m)<f0(x1)/1.5)
n <- 200
y <- x1[ind][1:n]
tmp0 <- awsdens(y,440,20,hmax=2000)
plot(tmp0$xgrid[[1]],tmp0$dens,type="l",lwd=2,
ylim =range(0,1.5,tmp0$dens),xlab="x",ylab="Density")
lines(tmp0$xgrid[[1]],f0(tmp0$xgrid[[1]]),lty=3,col=2,lwd=2)
title("Estimated and true density (n=200)")
###
### bivariate density estimation
###
f1 <- function(x,y) 7.5*pmax(x*(1-x^2-y^2),0)*(x>0)*(y>0)
set.seed(1)
m <- 10000
x1 <- runif(m)
x2 <- runif(m)
fx12 <- f1(x1,x2)
ind <- (runif(m)<f1(x1,x2)/.385/7.5)
n <- 2500
y <- rbind(x1[ind],x2[ind])[,1:n]
tmp <- awsdens(y,120,10,hmax=5)
image(tmp$xgrid[[1]],tmp$xgrid[[2]],tmp$dens,xlab="x1",ylab="x2",col=gray(.5+(255:0)/511),lwd=2)
# thats the estimated density on the grid
lines(seq(0,1,.01),sqrt(1-seq(0,1,.01)^2),col=2,lty=2,lwd=2)
lines(c(0,1),c(0,0),col=2,lty=2,lwd=2)
lines(c(0,0),c(0,1),col=2,lty=2,lwd=2)
# thats the boundary of the support
title("Estimated density (n=2500)")
# now add contour lines of the estimated density
contour(tmp$xgrid[[1]],tmp$xgrid[[2]],tmp$dens,nlevels=20,add=TRUE,col=1,lty=1,labcex=.1)
rm(f0,m,x1,ind,n,y,tmp0,f1,x2,fx12,tmp)
Run the code above in your browser using DataLab