I have the following algorithm to generate values for X and Y.
Step 1. Generate U1,U2~U(0,1)
Step 2. t=-beta*log(U1*U2)
Step 3. Generate U3~U(0,1)
Step 4. X=t*U3, Y=t-X
Notice you can compare the way to generate X and Y by generating U1 and U2 and defining X=-beta * log(U1) and Y=-beta * log(U2)
Here is my approach to implement this algorithm in R:
f<-function(alpha,beta){ # alpha=2, beta=3 for example
N<-1000
t<-rep(0,N)
X<-rep(0,N)
Y<-rep(0,N)
for(j in 1:N)
{
u<-runif(alpha)
t[j]<- -beta*log(prod(u))
U3<-runif(1)
X[j]<-t[j]*U3
Y[j]<-t[j]-X[j]
}
c<-list(X,Y)
return(c)
}
alpha<-2
beta<-3
y1<-f(alpha,beta)
hist(y1,freq=F,nclass=10,col="gray")
#COMPARISON, defining x and y directly as -beta*ln(u):
u1<-runif(1)
u2<-runif(1)
betaa<-2
x<- -betaa*log(u1)
y<- -betaa*log(u2)
x
y
The code works only in the numerical part, generates the 1000 values for both 'X' and 'Y'. Where I am having problems is in the part of the histogram because it does not show anything, marks an error
hist(y1,freq=F,nclass=10,col="gray") Error in hist.default(y1, freq = F, nclass = 10, col = "gray") : 'x' must be numeric
I don't understand why, how can I fix this?
Could someone please help?
Aucun commentaire:
Enregistrer un commentaire