sqrt(2*pi)*exp(-1/2)
knitr::opts_chunk$set(echo = TRUE)
set.seed(2022)
n = 10000
sample_x <- rep(NA,n)
for ( i in 1:n){
x = abs(rnorm(1,0,1))
u = runif(1,0,1)
while (u>f(x)/(M*2*dnorm(x))){
x = abs(rnorm(1,0,1))
u = runif(1,0,1)
}
sample_x[i] = x
}
f <- function(x){
2*x*exp(-x^2)
}
M = sqrt(2*pi)*exp(-1/2)
n = 10000
sample_x <- rep(NA,n)
for ( i in 1:n){
x = abs(rnorm(1,0,1))
u = runif(1,0,1)
while (u>f(x)/(M*2*dnorm(x))){
x = abs(rnorm(1,0,1))
u = runif(1,0,1)
}
sample_x[i] = x
}
mean(sample_x)
hist(sample_x)
hist(sample_x,probability = TRUE)
hist(sample_x,probability = TRUE)
x = seq(0,3.5,0.001)
lines(x,f(x),col="red")
30/16
sample_y <- rep(NA,n)
for ( i in 1:n){
y = runif(1,0,1)
u = runif(1,0,1)
while (u>f(x)/(M)){
y = runif(1,0,1)
u = runif(1,0,1)
}
sample_y[i] = y
}
sample_y <- rep(NA,n)
for ( i in 1:n){
y = runif(1,0,1)
u = runif(1,0,1)
while (u>f(y)/(M)){
y = runif(1,0,1)
u = runif(1,0,1)
}
sample_y[i] = y
}
hist(sample_y,probability = TRUE)
y = seq(0,3.5,0.001)
lines(y,f(y),col="red")
30/16
f <- function(x){
30*(y^2-2*y^3+y^4)
}
M = 1.875
sample_y <- rep(NA,n)
for ( i in 1:n){
y = runif(1,0,1)
u = runif(1,0,1)
while (u>f(y)/(M)){
y = runif(1,0,1)
u = runif(1,0,1)
}
sample_y[i] = y
}
hist(sample_y,probability = TRUE)
y = seq(0,3.5,0.001)
lines(y,f(y),col="red")
hist(sample_y,probability = TRUE)
y = seq(0,1,0.001)
lines(y,f(y),col="red")
