Polar Marsaglia RNG

#1
I was wondering whether someone might be willing to share their algorithm for number generation using polar Marsaglia method. I have been working on this for weeks and cannot do it as I just cannot overcome the problem of NA values in my loop.

Many thanks
Goran
 
#3
Phew...someone has given the following way of doing Marsaglia polar random numbers generation method which works prety smoothly:

marsaglia<- function(n = 1, mean = 0, sd = 1)
{
x <- vector("numeric", n) #x will be a vector of mode=numeric and length n
i <- 1
while(i <= n)

{ u <- runif(2, 0, 1) #our U(2n-1) and U(2n) with min = 0 and max = 1
v <- 2 * u - 1 # our V(2n-1) and V(2n)
s <- sum(v^2) #Vodd^2 + Veven^2

if (s < 1)
{w <- sqrt(-2 * log(s) / s) #w=sqrt(-2*s(nprim)/s(nprim))
z <- v * w # our Z(2n-1) and Z(2n)
x <- z[1] #our z(2n-1) becomes x

if ((i + 1) <= n) # if we can still fit one more value
{ x[i + 1] <- z[2] #our z(2n) becomes x[i+1]
i <- i + 1 } #increase value of i by 1 after conctenating z(2n)

i <- i + 1} #increase value of i by 1 after concatenating z(2n-1)
# in case (i+1)>n (which will bring loop to the end)
}
x * sd + mean #once we have our i x values multiply them by 1 and add 0 thus converting uniform distribution into normal
}