i have problems to perform my R-Code in OSX.
That’s my code:
i <- 1
while (i <= 20000) {
repeat{
z1=((runif(1,0,1)*2)-1)
z2=((runif(1,0,1)*2)-1)
h=z1**2+z2**2
if((h > 0) && (h <= 1)){break}
}
x[i] <- z1
y[i] <- z2
q[i] <- h
i <- i + 1
}
j <- 1
while (j <= 20000) {
h=sqrt((-2*ln(q[j]))/q[j])
p[j] <- h
j <- j + 1
}
a=x*p
b=y*p
points(a,b, pch=c(20,20),col=c("dark green","red"),cex=0.6)
When I initialize x,y,q,p and use the log, it works.
But why are there those errors, but why?
error in x[i] <- z1: object 'x' not fund
error: no function for "ln" fund
error: object 'x' not fund
error: object 'y' not fund
Here’s another approach. Your code should generally be faster if you reduce the number of times you need to do things iteratively. Specifically, all of your
runif(1,0,1)calls can be replaced by one big vector ofrunif()values, then subset the vector based on that.I used @Mark Miller’s function as the starting point and made the following modifications. Note, this can be improved further if the oversampler kept the good values from the previous set of random numbers and only filled in until
nwas reached, but this is pretty fast regardless. For the speed comparisons, I took his code verbatim and wrapped it infun2 <- function() {...}And the results
Starting with a new R session, copying and pasting the code above does not return an error. Here’s an example: