Physics with Mathematica

Tenth Class

Mercury in Transit: Next Monday morning

Generating random numbers

Remove["Global`*"]

The basics are simple

RandomReal[{1,5}]

RandomReal[{1,5}]

RandomReal[{1,5},5]

ranIntList=RandomInteger[{1,5},5]

There are many options, including managing the “seed”. Check the documentation

The Monte Carlo method

Remove["Global`*"]

Essentially a way of doing an integral, presumably one with many integration variables. Try using this technique to determine π.

nVals=10000;
xVals=RandomReal[{0,1},nVals];
yVals=RandomReal[{0,1},nVals];
zVals=RandomReal[{0,1},nVals];

rVals=Sqrt[xVals^2+yVals^2+zVals^2];

Count the points inside the unit sphere

nInsideSphere=Length[Select[rVals,#<1.0&]]

The fraction of points inside the sphere  is the ratio of the volume of the unit sphere in one octant, divide by the volume of the unit cube.

πEstimage=N[8 (3/4) nInsideSphere/nVals]

To get a better estimate, use more points, or many trials and average the result.

Generating distributions

Remove["Global`*"]

A “Probability Distribution Function” (aka PDF) describes the way random numbers can be distributed when their “randomness” follows a pattern. To generate random numbers according to some PDF, you need to generate raw random numbers and then invert the integral of the PDF to get a different number generated according to the distribution. (Textbooks can explain this much more thoroughly.)

Mathematica provides you a simple way to generate random numbers according to some distribution, for a large number of built-in PDFs.

μ=2.5;
vals=RandomVariate[PoissonDistribution[μ],10]

vals=RandomVariate[PoissonDistribution[μ],1000];
Histogram[vals]

N[Mean[vals]]

Other common distributions are NormalDistribution and BinomialDistribution but there are many others.