I have a joint p.d.f. And I am now comparing the theoretical value of the conditional probability and the empirical value which I ran the Monte Carlo Approach. I have to do this in replications 10,000, 100,000, and 1,000,000 draws. May I ask how to put replications in the R code?
Also, for the last step, the conditional probability, I was using Monte Carlo Approach to do it. Is there any R code which I can use for multivariate Uniform distribution to calculate the conditional probability?
Any suggestions would be highly appreciated! Thanks!!
My code was as below:
# f(x.y) = (1/4)*xy, 0<x<2, 0<y<2
# Find P(A) = P(X>1)
f <- function(x){(1/2)*x} # Marginal P(X)
probE <-integrate(f, lower = 1, upper = 2)
cat('\n Pr[ 1 < X ] is \n')
print(probE)
n <- 10000
x<-runif(n, 1,2)
probE.MC <- ((2-1)/n)*sum((1/2)*x)
cat('\n Monte Carlo Pr[1< X ] =',probE.MC,'\n')
# Find P(B) = P(Y<1)
f <- function(y){(1/2)*y} # Marginal P(Y)
probB <-integrate(f, lower = 0, upper = 1)
cat('\n Pr[ 1< Y ] is \n')
probB
typeof(probB)
n <- 10000
y<-runif(n, 0,1)
probB.MC <- ((1-0)/n)*sum((1/2)*y)
cat('\n Monte Carlo Pr[Y < 1] =',probB.MC,'\n')
# Pr[A intersect B]
# P[X>1 and Y <1]
f <- function(x,y){return((1/4)*x*y)}
n <- 100000
a11<-1; a12 <-2; a21 <- 0; a22 <-1
x <-runif(n, a11, a12)
y <- runif(n,a21, a22)
probMC <- ((a12-a11)*(a22-a21)/n)*sum(f(x,y))
probMC
typeof(probMC)
# P[A|B] = p[A intersect B]/ P(B)
probAB <- probMC/probB
First, I reformatted the functions and gave them separate names.
fX <- function(x) {
0.5 * x # Marginal P(X)
}
# Find P(B) = P(Y<1)
fY <- function(y) {
0.5 * y # Marginal P(Y)
}
fXY <- function(x, y) {
1 / length(x) * sum(0.25 * x * y) # joint X,Y
}
The simplest way to do multiple runs is to wrap the MC code in a for loop and save each calculation in an array. Then, at the end, take the mean of the stored values.
So for P[A] you have:
n <- 10000
probA.MC <- numeric(n) # create the array
for (i in 1:10000) {
x<-runif(n, 1,2)
probA.MC[i] <- ((2-1) / n) * sum(0.5 * x)
}
cat('\n Monte Carlo Pr[1 < X] =',mean(probA.MC),'\n')
(I assume probE.MC should have been probA.MC.) The result was Monte Carlo Pr[1 < X] = 0.7500088
. The code is analogous for P[B] and that result as Monte Carlo Pr[Y < 1] = 0.2499819
.
For the joint probability we use fXY.
n <- 10000
probMC <- numeric(n)
for (i in 1:10000) {
x <- runif(n, 1, 2)
y <- runif(n, 0, 1)
probMC[i] <- ((a12-a11) * (a22-a21)) * fXY(x, y)
}
cat('\n Monte Carlo Pr[X,Y] =',mean(probMC),'\n')
This result was Monte Carlo Pr[X,Y] = 0.1882728
.
The last calculation you did should read as follows (note the probB$value from the integration result):
# P[A|B] = p[A intersect B]/ P(B)
probAB <- mean(probMC) / probB$value
print(probAB)
This calculation yielded the result 0.7530913
.