0
$\begingroup$

I have to construct functions to obtain random numbers from a Gaussian Distribution with mean $\mu$ and variance $\sigma^2$ by using box-muller method and testing the function by sampling from a Gaussian with $\mu=10$ and $\sigma^2=5$. I have to plot the histograms together from a sufficient number of samples with the given distribution function. However, I cannot use NormalDistribution[$\mu$,$\sigma$].

Any ideas on how to do this would be highly appreciated.

For the box-muller method I managed to get this code:

u1 = RandomReal[{0, 1}, 20];
u2 = RandomReal[{0, 1}, 20];
r = Sqrt[-2*Log[u1]];
v = 2*Pi*u2;
x = r*Cos[v]
y = r*Sin[v]
$\endgroup$
1
  • 4
    $\begingroup$ Since this must clearly be some form of homework exercise, please show us what you've tried so far in code, and add references and explanations of the relevant algorithms. It's unlikely that somebody will just do this for you otherwise. $\endgroup$
    – MarcoB
    Commented Jan 25, 2022 at 13:24

1 Answer 1

1
$\begingroup$

With only slight modification to your equations for the box-muller method:

n = 1000;
mu = 10;
sigma = Sqrt[5];
SeedRandom[1];
u1 = RandomReal[{0, 1}, n];
u2 = RandomReal[{0, 1}, n];
r = sigma Sqrt[-2*Log[u1]];
v = 2*Pi*u2;
x = r*Cos[v] + mu
y = r*Sin[v] + mu
StandardDeviation /@ {x, y}^2
Mean /@ {x, y}

For n = 1000 samples and with RandomSeed[1], the sigma squared of x and y respectively is {5.08208, 4.83115} and the mean of x and y respectively is {9.95581, 10.0357}

We can make a histogram and compare it to the normal distribution like this:

Show[Plot[
  1/(sigma Sqrt[2 Pi]) Exp[-1/2 ((x - mu)/sigma)^2], {x, 0, 20}, 
  PlotLegends -> {"Normal Distribution"}],
 Histogram[{x, y}, Automatic, "PDF", ChartLegends -> {"X", "Y"}]]

enter image description here

With n = 1,000,000 samples and changing the bin width specification from "Automatic" to {.1} we get a smoother graph. enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.