Simulation of Continuous Random Variables

Here is the module that simulates the value of random variable X with the distribution from class:

simX[]:=Module[{},
u=RandomReal[];
If[u≤1/2,x=-1+Sqrt[2u],x=1-Sqrt[2-2u]];
Return[x]
]

simX[]

Let's simulate 10,000 values of X:

xvals=Table[simX[],10000]

Make a histogram of the simulated values. It has the same shape as our desired density function!

Histogram[xvals,20,"PDF"]

Simulating Brownian Motion

We can use values of X as “steps” in a simulation of a particle moving randomly left and right on the number line.

positions = {0};
Do[
AppendTo[positions, simX[] + positions[[-1]]],
500]

positions

ListLinePlot[positions, AxesLabel->{"step","position"}]

Animate[NumberLinePlot[{positions[[i]]},{x,-10,10},PlotStyle->PointSize[0.03]],{i,1,Length[positions],1},AnimationRate->20]

Find time until the particle moves a net distance of 10 units from the origin

We didn’t talk about this in class, but it was 2(b) on the worksheet from October 21.

timeToTen[]:=Module[{pos=0, time = 0},
While[Abs[pos]<10,
pos+=simX[];
time+=1
];
Return[time]
]

timeToTen[]

tenVals=Table[timeToTen[],1000]

Mean[tenVals]//N