MATLAB: Can anyone help me to find the mistake in this code

marsaglia

Hello everybody; Can anyone help me to find the mistake in this code for this question? Q: Generate a sample z1,z2,….,z100 from the standard normal distribution , by using (Marsaglia-Bray method) Matlab code:
rand('state',1); N = 200000;
U1 = rand(N,1); U2 = rand(N,1);
% Compute two vectors of in [?1, +1] equally distributed random variables
W1 = 2*U1 - ones(N,1);
W2 = 2*U2 - ones(N,1);
% Compute the set I of indices for which W1 2 + W2 2 < 1
W = W1.^2 + W2.^2;
I = find(W<1);
% Compute two standard normally distributed random variables
V = V(I);
Z1 = V1(I).*sqrt(-2.*log(V)./V);
Z2 = V2(I).*sqrt(-2.*log(V)./V);
% Generation of histograms
hist(Z1,0.0:0.05:1.0);
hist(Z2,0.0:0.05:1.0);
Thank you

Best Answer

Why the switch from W to V? Seems to me you should be using W all the way through. E.g.,
W = W(I);
Z1 = W1(I).*sqrt(-2.*log(W)./W);
Z2 = W2(I).*sqrt(-2.*log(W)./W);
Related Question