Professional Documents
Culture Documents
Assignment: Monte Carlo Simulations 1
Assignment: Monte Carlo Simulations 1
1. CODE:
# LECTURE 6 STAT 106
#Rishav Chakrabarti, roll no. = 1
#Assignment
#a)
x= seq(90:110) #stores a vector of 21 values from 90 to 110 in x
length(x) #gives length of x
y= x + rnorm(length(x)) #randomises y w.r.t x by adding 21 random values from std. normal
distn
plot(y~x) #plots y on x
lm(y~x) #gives regression of y on x
slopesamp= function(N){
slope= numeric(N)
for (i in 1:N) {
y=x + rnorm(length(x))
y.lm= lm(y~x)
slope[[i]] = as.vector(y.lm$coefficients[2])
}
slope
} #defines a function based on sample size which gives least square estimates of the slope
slopesamp(50) #slopes for samp size 50
plot(density(slopesamp(50))) #plots density of slope for samp size 50
mean(slopesamp(50)) #mean of slope for samp size 50
sd(slopesamp(50)) #std dev of slope for samp size 50
sd(slopesamp(50))/sqrt(50) #gives std error for slope estimator for samp size 50
#b)
#we study the means and standard errors of the slope depending on the sample size
mean(slopesamp(50))
sd(slopesamp(50))/sqrt(50)
mean(slopesamp(100))
sd(slopesamp(100))/sqrt(100)
mean(slopesamp(200))
sd(slopesamp(200))/sqrt(200)
mean(slopesamp(400))
sd(slopesamp(400))/sqrt(400)
mean(slopesamp(800))
sd(slopesamp(800))/sqrt(800)
mean(slopesamp(1000))
sd(slopesamp(1000))/sqrt(1000)
#gives means and standard errors of slope estimator for sample sizes 50, 100, 200, 400, 800
and 1000 respectively
#we see that the mean is approximately 1 and the standard error keeps decreasing
progressively with the increase in sample size
#c)
varsamp = function(N){
sigma2= numeric(N)
for (i in 1:N) {
y=x + rnorm(length(x))
y.lm= lm(y~x)
sigma2[[i]] = as.vector((summary(y.lm)$sigma)^2)
}
sigma2
}
#defines a function based on sample size which gives least square estimates of the variance
mean(varsamp(50))
sd(varsamp(50))/sqrt(50)
mean(varsamp(100))
sd(varsamp(100))/sqrt(100)
mean(varsamp(200))
sd(varsamp(200))/sqrt(200)
mean(varsamp(400))
sd(varsamp(400))/sqrt(400)
mean(varsamp(800))
sd(varsamp(800))/sqrt(800)
mean(varsamp(1000))
sd(varsamp(1000))/sqrt(1000)
#gives means and standard errors of LS variance estimator for sample sizes 50, 100, 200,
400, 800 and 1000 respectively
#we see that the mean is approximately 1 and the variance decreases progressively with the
increase in sample size
2. OUTPUT
> # LECTURE 6 STAT 106
> #Rishav Chakrabarti, roll no. = 1
> #Assignment
> #a)
> x= seq(90:110) #stores a vector of 21 values from 90 to 110 in x
> length(x) #gives length of x
[1] 21
> y= x + rnorm(length(x)) #randomises y w.r.t x by adding 21 random values from std.
normal distn
> plot(y~x) #plots y on x
> lm(y~x) #gives regression of y on x
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
0.1499 0.9770
>
> y= x + rnorm(length(x)) #randomizes once again
> lm(y~x) #regression model of y on x
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
-0.6563 1.0300