SlideShare a Scribd company logo
1 of 6
Download to read offline
Computational Physics 301: Exercise 3 - Random Numbers
and Monte Carlo
Thomas Wigg
March 29, 2014
Department of Physics, University of Bristol, Bristol,
UK
Abstract
This exercise was primarily concerned with the use of
random number generators. The rst part of the exer-
cise required that two dierent methods, the analytical
and 'accept/reject' methods, were used to create a sinu-
soidal distribution of random numbers from a uniform
distribution and their eectiveness compared. Whilst
both provided a very good sinusoidal t (with R2
very
close to one) with a large number of test points, it was
concluded that the 'accept/reject' method may be more
appropriate generally, as problems can arise with the
evalutation and inversion of certain aspects of the an-
alytical method. The nal part of the exercise was to
model a nuclear physics experiment in which the distri-
bution of gamma ray counts recorded in a detector pro-
duced by a beam of decaying nuclei was calculated using
Monte Carlo techniques. The resolution of the detector
was also accounted for using Gaussian smearing. It was
concluded that by applying the smearing, the calculated
distribution became much less precise and less indicative
of the true distribution: the resolution of the detector
must be improved to provide a genuine representation of
the distribution of counts recorded.
1 Random Numbers in a Distribu-
tion
In general, computational random number generators
produce output values within a set range, for instance
between x0 and x1, with a uniform distribution P(x).
The distribution P(x) may be transformed into an al-
ternative distribution P (x ), within the range x0 and
x1, by each of the following methods.
1.1 Analytical Distribution Transforma-
tion
Provided that both P(x) and P (x ) are normalised, the
cumulative distributions up to the generated values are
equivalent, such that
xreqˆ
x0
P (x )dx =
xgenˆ
x0
P(x)dx , (1)
where xreq is the value which the generated value xgen is
transformed into. As P(x) is stated as being a uniform
distribution, the right hand side of equation 1 is simply
equal to xgen. By dening the left hand side of this
equation such that
xreqˆ
x0
P (x )dx = Q(xreq) , (2)
equation 1 can be simplied to
Q(xreq) = xgen . (3)
It then follows that the equation to obtain xreq can
simply be written
xreq = Q−1
(xgen) . (4)
1.2 Accept/Reject Method
This method is similar to the standard Monte Carlo
method of integration[1] and provides another way of
converting a uniform distribution of generated random
numbers to an alternative distribution.
First, a uniform random number x is generated.
Next, another uniform random number y is generated in
the range 0 to ymax, where ymax is greater than, or equal
to, the maximum possible value of P (x ). The value of
x is accepeted if y  P (x ), else it is rejected and not
recorded. By this method the distribution P (x ) is built
up from the accepted values of x .
1
Figure 1: Table comparing the performance of many of
the random number generators available in the GSL li-
braries, showing the number of integers and double pre-
cision oating point numbers each is able to generate a
second[2].
1.3 Task 1: Generating Random Angles
in a Sinusoidal Distribution
This task was to generate random angles in the range
0  θ  π using the two methods described in sec-
tion 1.1 and 1.2 in distributions that are proportional
to sin(θ). For both methods, a uniform random gen-
erator from the GNU Scientic Library (GSL)[2] was
utilised. The GSL libraries oer a selection of random
generators and the 'gsl_rng_taus2' generator, a max-
imally equidistributed combined Tausworthe generator,
was chosen for use in this case. Figure 1 shows the speed
of the various generators oered by the GSL libraries:
the taus generator is the fastest simulation quality gen-
erator and the taus2 was chosen as it utilises exactly the
same generation algorithm as this but with an improved
seeding procedure[3].
The numbers generator by these GSL-based functions
are only pseudorandom in as much as they can only pro-
duce a nite number of values before they repeat them-
selves. In the case of the taus-based generators, 288
values can be generated before this repetition occurs.
Should more values than the limit of the given func-
tion be required, it is possible to change the seed of the
generator after the rst repetition and a dierent set of
pseudorandom numbers will be generated. In the case
of this task however, the number of random values re-
quired will be much less than 288
so this does not need
to be considered.
Once the chosen taus2 generator was set, the
'gsl_rng_uniform_pos' function was used. This func-
tion returns a set of uniformly distributed random num-
bers between, but not including, zero and one. This was
most appropriate as the task asked for random angles be-
tween zero and π but not including the two extremeties
of the range.
1.3.1 Transforming to a Sinusoidal Distribution
Using the Analytical Method
As the distribution P (x ) is required to be proportional
to sin(θ), the equation for Q(xreq) can be written
Q(xreq) =
1
2
xreqˆ
0
sin(x )dx , (5)
where the 1
2 coecient is present due to the normalisa-
tion of the distribution over the range 0  sin(x )  1
(corresponding to generated x values in the range 0 
x  π).
Using an appropriate substitution of equation 5 into
equation 3, the relationship
2xgen =
xreqˆ
0
sin(x )dx (6)
can be derived. Performing the integral and then making
the required rearrangement, the nal equation
xreq = arccos(1 − 2xgen) , (7)
to nd the sinusoidally distributed random numbers, can
be reached. Equation 7 can simply be entered into the
routine to generate a series of sinusoidally distributed
random numbers from the uniformly distributed ran-
dom numbers generated by the generator function. The
distrubtions produced by this routine for two dierent
numbers of output values can be seen in gures 2 and 3.
1.3.2 Generating a Sinusoidal Distribution us-
ing the Accept/Reject Method
In the case of this task, the required range for the gen-
erated angles is 0  x  π, corresponding to a maximal
range of 0  P (x )  1. Values of x were then gener-
ated by simply multiplying the values returned by the
generator by π. The value of ymax was then set to 1
(as ymax = sin π
2 ), random numbers were generated
in the range 0  y  1 and the accept/reject method
was applied to these values as detailed above. The out-
put distributions for a routine utilising the accept/reject
method for two dierent numbers of test values can be
seen in gures 4 and 5.
1.3.3 Comparing the Analytical and Ac-
cept/Reject Methods of Generating a
Sinusoidal Distribution
It is evident from comparing gures 2 and 4 and gures
3 and 5 that the greater the number of random angles
2
Figure 2: Histogram showing the sinusoidal distribution
of random angles, x , in the range 0  x  π, generated
by a program utilising the analytical method of trans-
forming a uniform distribution of random numbers. 500
angles were generated and the seed for the random num-
ber generator was 0. A sinusoidal t has been applied to
the data - the resulting t has an R2
value of 0.78131.
Figure 3: Histogram showing the sinusoidal distribution
of random angles, x , in the range 0  x  π, gen-
erated by a program utilising the analytical method of
transforming a uniform distribution of random numbers.
1000000 angles were generated and the seed for the ran-
dom number generator was 0. A sinusoidal t has been
applied to the data - the resulting t has an R2
value of
0.99989.
Figure 4: Histogram showing the sinusoidal distribution
of random angles, x , in the range 0  x  π, gener-
ated by a program utilising the 'accept/reject' method
of generating a distribution of random numbers. 808 an-
gles were generated, of which 500 were accepted and the
seed for the random number generator was 0. A sinu-
soidal t has been applied to the data - the resulting t
has an R2
value of 0.75930.
Figure 5: Histogram showing the sinusoidal distribution
of random angles, x , in the range 0  x  π, gener-
ated by a program utilising the 'accept/reject' method of
generating a distribution of random numbers. 1571201
angles were generated, of which 1000000 were accepted
and the seed for the random number generator was 0. A
sinusoidal t has been applied to the data - the resulting
t has an R2
value of 0.99992.
3
generated, the closer the resulting distribution is to si-
nusoidal for both methods. To determine how close each
distribution is to sinusoidal quintitively, a t must be a
applied to the data. This has been done in gures 2
to 5 and from this an R2
value (coecient of determi-
nation) is returned; the closer this R2
value is to one,
the better the t. For a distribution of ve hundred
randomly generated angles, the analytical method re-
turned an R2
value of 0.78131 whilst the 'accept/reject'
method returned an R2
value of 0.75930. This result
shows that, in this case, the analytical method provides
a marginally better sinusoidal distribution than the 'ac-
cept/reject' method. However, for such a relatively small
number of generated angles, it is not fair to make a
genuine comparison between the two methods. For a
much greater distribution of one million generated an-
gles, the R2
values for the analytical and 'accept/reject'
method were 0.99989 and 0.99992 respectively. These
values show that both are close to perfect sinusoidal dis-
tributions with little deviation from the sinusoidal t. In
this case again, both distributions displayed very similar
R2
values, with the 'accept/reject' method providing a
marginally better t this time. The dierence in the R2
values was so minute though, that it is not possible to
choose a preferred method simply from this. Looking at
the other aspects of each method, the analytical method
has the disadvantage that the denite integral Q(xreq)
may sometimes be dicult to evaluate and invert and so,
because of its simple nature, the 'accept/reject' method
may be preferable.
2 Simulations
When modelling physical problems, it is often most ap-
propriate to simulate the experimental data point by
point: this is known as Monte Carlo simulation. When
it is necessary to model changing or unknowable param-
eters, random number generators are used to produce
these variables.
2.1 Physics Problem 1: Gamma Ray
Events from Unstable Nuclei
Recorded in a Detector
This nuclear physics experiment to be simulated consists
of a beam of unstable nuclei injected at 2000ms−1
trav-
elling in the z direction. The nuclei decay with a mean
lifetime of 520µs producing a gamma ray. The produced
gamma rays are unpolarised and are therefore emitted
isotropically, to be recorded by a detector situated 2m
from the injection point with a resolution of 10cm in
the x plane and 30cm in the y plane. The experimental
setup can be seen in gure 6.
The aim of this task was to create a routine that mod-
elled the distribution of gamma rays recorded in the de-
tector. It is assumed that the only gamma rays detected
Figure 6: Diagram showing the experimental setup of
the detector array for the nuclear physics experiment
described in Physics Problem 1.
Figure 7: Histogram showing the decay length, or the
distance travelled before decaying, of 1,000,000 nuclei
in the beam described in Physics Problem 1 with no
detector array present. The bin width is 0.2m.
Figure 8: Diagram showing the spherical coordinate sys-
tem used to dene the direction of gamma ray emission
in Physics Problem 1.
4
are from the decaying nuclei (no background counts) and
that the nuclei never get scattered before reaching the
detector (all nuclei decay at (x = 0, y = 0, z)). The
nuclei in the beam are subject to the exponential decay
law[4], which means the rate of decrease in the number
of nuclei is proportional to the number of nuclei at that
point in time, such that
dN
dt
= −λN (8)
= −
N
τ
, (9)
where, in the case of this experiment, N is the number
of nuclei left in the beam, λ is the exponential decay
constant and τ is the mean lifetime of the nuclei in the
beam. With the mean lifetime given, the GSL function
'gsl_ran_exponential' was used to generate random life-
times for the nuclei present in the beam from an expo-
nential distribution, with a mean equal 520µs. Figure
7 shows the corresponding decay length of the generate
decay times for one million simulated nuclei. As is to
be expected with such a large sample size, the R2
value
of an exponential decay t to the histogram is 0.99999,
showing a close to perfect t to the required exponential
decay law.
It is evident from gure 7 that a the decay length of
many of the nuclei is greater than two metres, mean-
ing that the nuclei will not have decayed by the point
it reaches the detector. It is assumed that nuclei that
do not decay before the detector will not produce any
gamma rays and do not register as an event in the de-
tector. For this reason, the routine excludes any nuclei
that are simulated to have a decay length greater than
two metres. For the nuclei that do decay before reach-
ing the detector, the direction in which the gamma ray
is emitted is generated randomly in three dimensions by
generating random values of the polar θ and azimuthal
φ angles to give a direction in spherical coordinates. A
diagram of the spherical coordinate system used can be
seen in gure 8. φ was generated from a uniform dis-
tribution with the range [0, 2π). θ was generated in the
range [0, π] but not using a uniform distribution, as the
area element dΩ = sinθdφdθ is a function of θ and would
therefore result in more points being generated close to
the poles of the coordinate sphere. To account for this,
the values of θ were generated by transforming a uniform
distribution into a sinusoidal distribution using the an-
alytical method used in Task 1. The analytical method
was chosen over the 'accept/reject' method as to avoid
the inevitable loss of data points caused by the nature
of the method. This could be avoided using a loop to
verify that any nuclei that decay before the detector pro-
duce a gamma that meets the restrictions on the angle
θ, but it was decided that this would make the routine
unnecessarily complicated.
The routine next excluded all gamma rays with θ ≥ π
2 ,
as for values of θ in this range, the gamma rays are
travelling in the negative z direction and so would never
reach the detector. It is worth noting that it has been
assumed that, should a nucleus decay after the detector
and produce a gamma ray travelling in the negative z
direction (back towards the detector), that the gamma
ray is not recorded should it return and hit the detector.
Spherical coordinates can be transformed to their
catersian counterparts using the three equations[5]
x = −rsinθcosφ , (10)
y = rsinθsinφ , (11)
z = rcosθ , (12)
where the -1 coecient of equation 10 comes from the
fact that the x-axis of the detector array is inverted com-
pared to the x-axis of the spherical system in which the
directions representing the emitted gamma rays path of
travel are produced.
Equation 12 can be rearranged to give r in terms of
z, the distance between the nucleus decay point and the
detector, such that
r =
z
cosθ
. (13)
By substituting this into equations 10 and 11, it is
possible to derive equations for the (x, y) coordinates of
the gamma ray when level with the detector array, such
that
x = −ztanθcosφ , (14)
y = ztanθsinφ . (15)
Using equations 14 and 15, it is straightforward to
determine whether the gamma ray hits the detector by
checking whether the nal (x, y) coordinates lie within
the connes of the detector array. The distribution of
gamma rays detected can be seen in gure 9.
The result in gure 9 does not account for the nite
resolution of the detector array. The resolution of the
detector is stated as being 10cm in the x direction and
30cm in the y direction. The eects of the restricted res-
olution are modelled by smearing the (x, y) coordinates
of each gamma ray detected. This is achieved by adding
a random Gaussian distribution term to each of the x
and y coordinates, where the standard deviation of each
Gaussian term is equal to the resolution of the detector
in that direction. The random Gaussian terms were gen-
erated using the 'gsl_ran_gaussian' function oered by
the GNU Scientic Library. The distribution of gamma
rays recorded by the detector, with smearing applied to
account for the resolution of the detector, can be seen in
gure 10.
5
Figure 9: Plot showing the distribution of gamma
rays recorded in the detector array, with dimensions of
3m × 3m, in a simulation of the experiment described
in Physics Problem 1. 1,000,000 nuclei were present in
the simulated beam, of which 854,438 decayed before
reaching the detector, with 179,928 actually hitting the
detector array. The bin width was 0.1m and the seed of
the random number generator was set to zero.
Figure 10: Plot showing the distribution of gamma
rays recorded in the detector array, with dimensions of
3m × 3m, in a simulation of the experiment described
in Physics Problem 1. 1,000,000 nuclei were present in
the simulated beam, of which 853,550 decayed before
reaching the detector, with 177,067 actually hitting the
detector array. The bin width was 0.1m and the seed of
the random number generator was set to zero.
It is clear from comparing gures 9 and 10 that smear-
ing the data to account for the resolution of the detector
has tangible eects on the distribution recorded, which
manifest themselves as a general broadening of the con-
tours in both directions, with this being more prolic
in the y direction compared to the x. This is to be ex-
pected, as the resolution in the y direction is three times
worse than that in the x direction, thus the contours
appear elliptical. Because of this, it is evident that the
resolution of the detector must be improved in order to
accurately represent the distribution of incident gamma
rays. In a physical context, a resolution of 30cm, which
equates to one tenth the width of the detector itself, is
not satisfactory for any genuine nuclear physics applica-
tion.
References
[1] Z. I. B. D. P. Kroese, T. Taimre, Handbook of Monte
Carlo Methods (John Wiley  Sons, 2011) p. 59.
[2] GNU Scientic Library (GSL), 1.13
(http://www.gnu.org/software/gsl) accessed:
20/03/2014.
[3] P. L'Ecuyer, Mathematics of Computation 68, 261
(1999).
[4] J. H. H. F. Yang, Modern Atomic and Nuclear
Physics, revised ed. (World Scientic Publishing Co.
Pte. Ltd., 2010) p. 404.
[5] B. J. J. E. N. I. Fisher, T. Lewis, Statistical Analysis
of Spherical Data, rst paperback ed. (Cambridge
University Press, 1993) p. 18.

More Related Content

What's hot

A new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributionsA new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributionsFrank Nielsen
 
Application of Numerical Methods (Finite Difference) in Heat Transfer
Application of Numerical Methods (Finite Difference) in Heat TransferApplication of Numerical Methods (Finite Difference) in Heat Transfer
Application of Numerical Methods (Finite Difference) in Heat TransferShivshambhu Kumar
 
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...qyjewyvu
 
83662164 case-study-1
83662164 case-study-183662164 case-study-1
83662164 case-study-1homeworkping3
 
Linear regression [Theory and Application (In physics point of view) using py...
Linear regression [Theory and Application (In physics point of view) using py...Linear regression [Theory and Application (In physics point of view) using py...
Linear regression [Theory and Application (In physics point of view) using py...ANIRBANMAJUMDAR18
 
Numerical
NumericalNumerical
Numerical1821986
 
International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)ijceronline
 
Solution of equations for methods iterativos
Solution of equations for methods iterativosSolution of equations for methods iterativos
Solution of equations for methods iterativosDUBAN CASTRO
 
Numerical differentation with c
Numerical differentation with cNumerical differentation with c
Numerical differentation with cYagya Dev Bhardwaj
 
2012 mdsp pr04 monte carlo
2012 mdsp pr04 monte carlo2012 mdsp pr04 monte carlo
2012 mdsp pr04 monte carlonozomuhamada
 
Quickselect Under Yaroslavskiy's Dual Pivoting Algorithm
Quickselect Under Yaroslavskiy's Dual Pivoting AlgorithmQuickselect Under Yaroslavskiy's Dual Pivoting Algorithm
Quickselect Under Yaroslavskiy's Dual Pivoting AlgorithmSebastian Wild
 
2012 mdsp pr08 nonparametric approach
2012 mdsp pr08 nonparametric approach2012 mdsp pr08 nonparametric approach
2012 mdsp pr08 nonparametric approachnozomuhamada
 
Hso201 a solutions to practice problem set 3-2015-16-ii
Hso201 a solutions to practice problem set 3-2015-16-iiHso201 a solutions to practice problem set 3-2015-16-ii
Hso201 a solutions to practice problem set 3-2015-16-iiOm Prakash Bankolia
 
Propagation of Error Bounds due to Active Subspace Reduction
Propagation of Error Bounds due to Active Subspace ReductionPropagation of Error Bounds due to Active Subspace Reduction
Propagation of Error Bounds due to Active Subspace ReductionMohammad
 

What's hot (20)

probability assignment help (2)
probability assignment help (2)probability assignment help (2)
probability assignment help (2)
 
A new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributionsA new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributions
 
Application of Numerical Methods (Finite Difference) in Heat Transfer
Application of Numerical Methods (Finite Difference) in Heat TransferApplication of Numerical Methods (Finite Difference) in Heat Transfer
Application of Numerical Methods (Finite Difference) in Heat Transfer
 
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...
Applied Statistics and Probability for Engineers 6th Edition Montgomery Solut...
 
83662164 case-study-1
83662164 case-study-183662164 case-study-1
83662164 case-study-1
 
CMB Likelihood Part 1
CMB Likelihood Part 1CMB Likelihood Part 1
CMB Likelihood Part 1
 
final_report
final_reportfinal_report
final_report
 
Statistical Method In Economics
Statistical Method In EconomicsStatistical Method In Economics
Statistical Method In Economics
 
Linear regression [Theory and Application (In physics point of view) using py...
Linear regression [Theory and Application (In physics point of view) using py...Linear regression [Theory and Application (In physics point of view) using py...
Linear regression [Theory and Application (In physics point of view) using py...
 
Numerical
NumericalNumerical
Numerical
 
International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)International Journal of Computational Engineering Research(IJCER)
International Journal of Computational Engineering Research(IJCER)
 
Solution of equations for methods iterativos
Solution of equations for methods iterativosSolution of equations for methods iterativos
Solution of equations for methods iterativos
 
Mechanical Engineering Assignment Help
Mechanical Engineering Assignment HelpMechanical Engineering Assignment Help
Mechanical Engineering Assignment Help
 
Numerical differentation with c
Numerical differentation with cNumerical differentation with c
Numerical differentation with c
 
2012 mdsp pr04 monte carlo
2012 mdsp pr04 monte carlo2012 mdsp pr04 monte carlo
2012 mdsp pr04 monte carlo
 
Quickselect Under Yaroslavskiy's Dual Pivoting Algorithm
Quickselect Under Yaroslavskiy's Dual Pivoting AlgorithmQuickselect Under Yaroslavskiy's Dual Pivoting Algorithm
Quickselect Under Yaroslavskiy's Dual Pivoting Algorithm
 
Statistics Homework Help
Statistics Homework HelpStatistics Homework Help
Statistics Homework Help
 
2012 mdsp pr08 nonparametric approach
2012 mdsp pr08 nonparametric approach2012 mdsp pr08 nonparametric approach
2012 mdsp pr08 nonparametric approach
 
Hso201 a solutions to practice problem set 3-2015-16-ii
Hso201 a solutions to practice problem set 3-2015-16-iiHso201 a solutions to practice problem set 3-2015-16-ii
Hso201 a solutions to practice problem set 3-2015-16-ii
 
Propagation of Error Bounds due to Active Subspace Reduction
Propagation of Error Bounds due to Active Subspace ReductionPropagation of Error Bounds due to Active Subspace Reduction
Propagation of Error Bounds due to Active Subspace Reduction
 

Similar to tw1979 Exercise 3 Report

Presentacion limac-unc
Presentacion limac-uncPresentacion limac-unc
Presentacion limac-uncPucheta Julian
 
Variation of peak shape and peak tailing in chromatography
Variation of peak shape and peak tailing in chromatographyVariation of peak shape and peak tailing in chromatography
Variation of peak shape and peak tailing in chromatographymanjikra
 
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...Thomas Templin
 
Roots of equations
Roots of equationsRoots of equations
Roots of equationsMileacre
 
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...IJECEIAES
 
Comparing the methods of Estimation of Three-Parameter Weibull distribution
Comparing the methods of Estimation of Three-Parameter Weibull distributionComparing the methods of Estimation of Three-Parameter Weibull distribution
Comparing the methods of Estimation of Three-Parameter Weibull distributionIOSRJM
 
Solving the Poisson Equation
Solving the Poisson EquationSolving the Poisson Equation
Solving the Poisson EquationShahzaib Malik
 
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAScientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAAhmed Gamal Abdel Gawad
 
Ill-posedness formulation of the emission source localization in the radio- d...
Ill-posedness formulation of the emission source localization in the radio- d...Ill-posedness formulation of the emission source localization in the radio- d...
Ill-posedness formulation of the emission source localization in the radio- d...Ahmed Ammar Rebai PhD
 
First paper with the NITheCS affiliation
First paper with the NITheCS affiliationFirst paper with the NITheCS affiliation
First paper with the NITheCS affiliationRene Kotze
 
Performance of Spiked Population Models for Spectrum Sensing
Performance of Spiked Population Models for Spectrum SensingPerformance of Spiked Population Models for Spectrum Sensing
Performance of Spiked Population Models for Spectrum SensingPolytechnique Montreal
 
Chapter 4(1).pptx
Chapter 4(1).pptxChapter 4(1).pptx
Chapter 4(1).pptxmahamoh6
 
Data Driven Choice of Threshold in Cepstrum Based Spectrum Estimate
Data Driven Choice of Threshold in Cepstrum Based Spectrum EstimateData Driven Choice of Threshold in Cepstrum Based Spectrum Estimate
Data Driven Choice of Threshold in Cepstrum Based Spectrum Estimatesipij
 
Algorithms for Global Positioning
Algorithms for Global PositioningAlgorithms for Global Positioning
Algorithms for Global PositioningKevin Le
 
B02110105012
B02110105012B02110105012
B02110105012theijes
 
The International Journal of Engineering and Science (The IJES)
 The International Journal of Engineering and Science (The IJES) The International Journal of Engineering and Science (The IJES)
The International Journal of Engineering and Science (The IJES)theijes
 
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdf
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdfLecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdf
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdfmgeneralwork
 

Similar to tw1979 Exercise 3 Report (20)

Presentacion limac-unc
Presentacion limac-uncPresentacion limac-unc
Presentacion limac-unc
 
Variation of peak shape and peak tailing in chromatography
Variation of peak shape and peak tailing in chromatographyVariation of peak shape and peak tailing in chromatography
Variation of peak shape and peak tailing in chromatography
 
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...
Using the Componentwise Metropolis-Hastings Algorithm to Sample from the Join...
 
Roots of equations
Roots of equationsRoots of equations
Roots of equations
 
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...
Diagnosis of Faulty Sensors in Antenna Array using Hybrid Differential Evolut...
 
Comparing the methods of Estimation of Three-Parameter Weibull distribution
Comparing the methods of Estimation of Three-Parameter Weibull distributionComparing the methods of Estimation of Three-Parameter Weibull distribution
Comparing the methods of Estimation of Three-Parameter Weibull distribution
 
Solving the Poisson Equation
Solving the Poisson EquationSolving the Poisson Equation
Solving the Poisson Equation
 
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAScientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
 
v39i11.pdf
v39i11.pdfv39i11.pdf
v39i11.pdf
 
Ill-posedness formulation of the emission source localization in the radio- d...
Ill-posedness formulation of the emission source localization in the radio- d...Ill-posedness formulation of the emission source localization in the radio- d...
Ill-posedness formulation of the emission source localization in the radio- d...
 
First paper with the NITheCS affiliation
First paper with the NITheCS affiliationFirst paper with the NITheCS affiliation
First paper with the NITheCS affiliation
 
Makalah ukuran penyebaran
Makalah ukuran penyebaranMakalah ukuran penyebaran
Makalah ukuran penyebaran
 
Performance of Spiked Population Models for Spectrum Sensing
Performance of Spiked Population Models for Spectrum SensingPerformance of Spiked Population Models for Spectrum Sensing
Performance of Spiked Population Models for Spectrum Sensing
 
Chapter 4(1).pptx
Chapter 4(1).pptxChapter 4(1).pptx
Chapter 4(1).pptx
 
Data Driven Choice of Threshold in Cepstrum Based Spectrum Estimate
Data Driven Choice of Threshold in Cepstrum Based Spectrum EstimateData Driven Choice of Threshold in Cepstrum Based Spectrum Estimate
Data Driven Choice of Threshold in Cepstrum Based Spectrum Estimate
 
Algorithms for Global Positioning
Algorithms for Global PositioningAlgorithms for Global Positioning
Algorithms for Global Positioning
 
Numeros complejos y_azar
Numeros complejos y_azarNumeros complejos y_azar
Numeros complejos y_azar
 
B02110105012
B02110105012B02110105012
B02110105012
 
The International Journal of Engineering and Science (The IJES)
 The International Journal of Engineering and Science (The IJES) The International Journal of Engineering and Science (The IJES)
The International Journal of Engineering and Science (The IJES)
 
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdf
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdfLecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdf
Lecxvvfdghdxbhhfdddghhhgfcvbbbbgdss 7.pdf
 

tw1979 Exercise 3 Report

  • 1. Computational Physics 301: Exercise 3 - Random Numbers and Monte Carlo Thomas Wigg March 29, 2014 Department of Physics, University of Bristol, Bristol, UK Abstract This exercise was primarily concerned with the use of random number generators. The rst part of the exer- cise required that two dierent methods, the analytical and 'accept/reject' methods, were used to create a sinu- soidal distribution of random numbers from a uniform distribution and their eectiveness compared. Whilst both provided a very good sinusoidal t (with R2 very close to one) with a large number of test points, it was concluded that the 'accept/reject' method may be more appropriate generally, as problems can arise with the evalutation and inversion of certain aspects of the an- alytical method. The nal part of the exercise was to model a nuclear physics experiment in which the distri- bution of gamma ray counts recorded in a detector pro- duced by a beam of decaying nuclei was calculated using Monte Carlo techniques. The resolution of the detector was also accounted for using Gaussian smearing. It was concluded that by applying the smearing, the calculated distribution became much less precise and less indicative of the true distribution: the resolution of the detector must be improved to provide a genuine representation of the distribution of counts recorded. 1 Random Numbers in a Distribu- tion In general, computational random number generators produce output values within a set range, for instance between x0 and x1, with a uniform distribution P(x). The distribution P(x) may be transformed into an al- ternative distribution P (x ), within the range x0 and x1, by each of the following methods. 1.1 Analytical Distribution Transforma- tion Provided that both P(x) and P (x ) are normalised, the cumulative distributions up to the generated values are equivalent, such that xreqˆ x0 P (x )dx = xgenˆ x0 P(x)dx , (1) where xreq is the value which the generated value xgen is transformed into. As P(x) is stated as being a uniform distribution, the right hand side of equation 1 is simply equal to xgen. By dening the left hand side of this equation such that xreqˆ x0 P (x )dx = Q(xreq) , (2) equation 1 can be simplied to Q(xreq) = xgen . (3) It then follows that the equation to obtain xreq can simply be written xreq = Q−1 (xgen) . (4) 1.2 Accept/Reject Method This method is similar to the standard Monte Carlo method of integration[1] and provides another way of converting a uniform distribution of generated random numbers to an alternative distribution. First, a uniform random number x is generated. Next, another uniform random number y is generated in the range 0 to ymax, where ymax is greater than, or equal to, the maximum possible value of P (x ). The value of x is accepeted if y P (x ), else it is rejected and not recorded. By this method the distribution P (x ) is built up from the accepted values of x . 1
  • 2. Figure 1: Table comparing the performance of many of the random number generators available in the GSL li- braries, showing the number of integers and double pre- cision oating point numbers each is able to generate a second[2]. 1.3 Task 1: Generating Random Angles in a Sinusoidal Distribution This task was to generate random angles in the range 0 θ π using the two methods described in sec- tion 1.1 and 1.2 in distributions that are proportional to sin(θ). For both methods, a uniform random gen- erator from the GNU Scientic Library (GSL)[2] was utilised. The GSL libraries oer a selection of random generators and the 'gsl_rng_taus2' generator, a max- imally equidistributed combined Tausworthe generator, was chosen for use in this case. Figure 1 shows the speed of the various generators oered by the GSL libraries: the taus generator is the fastest simulation quality gen- erator and the taus2 was chosen as it utilises exactly the same generation algorithm as this but with an improved seeding procedure[3]. The numbers generator by these GSL-based functions are only pseudorandom in as much as they can only pro- duce a nite number of values before they repeat them- selves. In the case of the taus-based generators, 288 values can be generated before this repetition occurs. Should more values than the limit of the given func- tion be required, it is possible to change the seed of the generator after the rst repetition and a dierent set of pseudorandom numbers will be generated. In the case of this task however, the number of random values re- quired will be much less than 288 so this does not need to be considered. Once the chosen taus2 generator was set, the 'gsl_rng_uniform_pos' function was used. This func- tion returns a set of uniformly distributed random num- bers between, but not including, zero and one. This was most appropriate as the task asked for random angles be- tween zero and π but not including the two extremeties of the range. 1.3.1 Transforming to a Sinusoidal Distribution Using the Analytical Method As the distribution P (x ) is required to be proportional to sin(θ), the equation for Q(xreq) can be written Q(xreq) = 1 2 xreqˆ 0 sin(x )dx , (5) where the 1 2 coecient is present due to the normalisa- tion of the distribution over the range 0 sin(x ) 1 (corresponding to generated x values in the range 0 x π). Using an appropriate substitution of equation 5 into equation 3, the relationship 2xgen = xreqˆ 0 sin(x )dx (6) can be derived. Performing the integral and then making the required rearrangement, the nal equation xreq = arccos(1 − 2xgen) , (7) to nd the sinusoidally distributed random numbers, can be reached. Equation 7 can simply be entered into the routine to generate a series of sinusoidally distributed random numbers from the uniformly distributed ran- dom numbers generated by the generator function. The distrubtions produced by this routine for two dierent numbers of output values can be seen in gures 2 and 3. 1.3.2 Generating a Sinusoidal Distribution us- ing the Accept/Reject Method In the case of this task, the required range for the gen- erated angles is 0 x π, corresponding to a maximal range of 0 P (x ) 1. Values of x were then gener- ated by simply multiplying the values returned by the generator by π. The value of ymax was then set to 1 (as ymax = sin π 2 ), random numbers were generated in the range 0 y 1 and the accept/reject method was applied to these values as detailed above. The out- put distributions for a routine utilising the accept/reject method for two dierent numbers of test values can be seen in gures 4 and 5. 1.3.3 Comparing the Analytical and Ac- cept/Reject Methods of Generating a Sinusoidal Distribution It is evident from comparing gures 2 and 4 and gures 3 and 5 that the greater the number of random angles 2
  • 3. Figure 2: Histogram showing the sinusoidal distribution of random angles, x , in the range 0 x π, generated by a program utilising the analytical method of trans- forming a uniform distribution of random numbers. 500 angles were generated and the seed for the random num- ber generator was 0. A sinusoidal t has been applied to the data - the resulting t has an R2 value of 0.78131. Figure 3: Histogram showing the sinusoidal distribution of random angles, x , in the range 0 x π, gen- erated by a program utilising the analytical method of transforming a uniform distribution of random numbers. 1000000 angles were generated and the seed for the ran- dom number generator was 0. A sinusoidal t has been applied to the data - the resulting t has an R2 value of 0.99989. Figure 4: Histogram showing the sinusoidal distribution of random angles, x , in the range 0 x π, gener- ated by a program utilising the 'accept/reject' method of generating a distribution of random numbers. 808 an- gles were generated, of which 500 were accepted and the seed for the random number generator was 0. A sinu- soidal t has been applied to the data - the resulting t has an R2 value of 0.75930. Figure 5: Histogram showing the sinusoidal distribution of random angles, x , in the range 0 x π, gener- ated by a program utilising the 'accept/reject' method of generating a distribution of random numbers. 1571201 angles were generated, of which 1000000 were accepted and the seed for the random number generator was 0. A sinusoidal t has been applied to the data - the resulting t has an R2 value of 0.99992. 3
  • 4. generated, the closer the resulting distribution is to si- nusoidal for both methods. To determine how close each distribution is to sinusoidal quintitively, a t must be a applied to the data. This has been done in gures 2 to 5 and from this an R2 value (coecient of determi- nation) is returned; the closer this R2 value is to one, the better the t. For a distribution of ve hundred randomly generated angles, the analytical method re- turned an R2 value of 0.78131 whilst the 'accept/reject' method returned an R2 value of 0.75930. This result shows that, in this case, the analytical method provides a marginally better sinusoidal distribution than the 'ac- cept/reject' method. However, for such a relatively small number of generated angles, it is not fair to make a genuine comparison between the two methods. For a much greater distribution of one million generated an- gles, the R2 values for the analytical and 'accept/reject' method were 0.99989 and 0.99992 respectively. These values show that both are close to perfect sinusoidal dis- tributions with little deviation from the sinusoidal t. In this case again, both distributions displayed very similar R2 values, with the 'accept/reject' method providing a marginally better t this time. The dierence in the R2 values was so minute though, that it is not possible to choose a preferred method simply from this. Looking at the other aspects of each method, the analytical method has the disadvantage that the denite integral Q(xreq) may sometimes be dicult to evaluate and invert and so, because of its simple nature, the 'accept/reject' method may be preferable. 2 Simulations When modelling physical problems, it is often most ap- propriate to simulate the experimental data point by point: this is known as Monte Carlo simulation. When it is necessary to model changing or unknowable param- eters, random number generators are used to produce these variables. 2.1 Physics Problem 1: Gamma Ray Events from Unstable Nuclei Recorded in a Detector This nuclear physics experiment to be simulated consists of a beam of unstable nuclei injected at 2000ms−1 trav- elling in the z direction. The nuclei decay with a mean lifetime of 520µs producing a gamma ray. The produced gamma rays are unpolarised and are therefore emitted isotropically, to be recorded by a detector situated 2m from the injection point with a resolution of 10cm in the x plane and 30cm in the y plane. The experimental setup can be seen in gure 6. The aim of this task was to create a routine that mod- elled the distribution of gamma rays recorded in the de- tector. It is assumed that the only gamma rays detected Figure 6: Diagram showing the experimental setup of the detector array for the nuclear physics experiment described in Physics Problem 1. Figure 7: Histogram showing the decay length, or the distance travelled before decaying, of 1,000,000 nuclei in the beam described in Physics Problem 1 with no detector array present. The bin width is 0.2m. Figure 8: Diagram showing the spherical coordinate sys- tem used to dene the direction of gamma ray emission in Physics Problem 1. 4
  • 5. are from the decaying nuclei (no background counts) and that the nuclei never get scattered before reaching the detector (all nuclei decay at (x = 0, y = 0, z)). The nuclei in the beam are subject to the exponential decay law[4], which means the rate of decrease in the number of nuclei is proportional to the number of nuclei at that point in time, such that dN dt = −λN (8) = − N τ , (9) where, in the case of this experiment, N is the number of nuclei left in the beam, λ is the exponential decay constant and τ is the mean lifetime of the nuclei in the beam. With the mean lifetime given, the GSL function 'gsl_ran_exponential' was used to generate random life- times for the nuclei present in the beam from an expo- nential distribution, with a mean equal 520µs. Figure 7 shows the corresponding decay length of the generate decay times for one million simulated nuclei. As is to be expected with such a large sample size, the R2 value of an exponential decay t to the histogram is 0.99999, showing a close to perfect t to the required exponential decay law. It is evident from gure 7 that a the decay length of many of the nuclei is greater than two metres, mean- ing that the nuclei will not have decayed by the point it reaches the detector. It is assumed that nuclei that do not decay before the detector will not produce any gamma rays and do not register as an event in the de- tector. For this reason, the routine excludes any nuclei that are simulated to have a decay length greater than two metres. For the nuclei that do decay before reach- ing the detector, the direction in which the gamma ray is emitted is generated randomly in three dimensions by generating random values of the polar θ and azimuthal φ angles to give a direction in spherical coordinates. A diagram of the spherical coordinate system used can be seen in gure 8. φ was generated from a uniform dis- tribution with the range [0, 2π). θ was generated in the range [0, π] but not using a uniform distribution, as the area element dΩ = sinθdφdθ is a function of θ and would therefore result in more points being generated close to the poles of the coordinate sphere. To account for this, the values of θ were generated by transforming a uniform distribution into a sinusoidal distribution using the an- alytical method used in Task 1. The analytical method was chosen over the 'accept/reject' method as to avoid the inevitable loss of data points caused by the nature of the method. This could be avoided using a loop to verify that any nuclei that decay before the detector pro- duce a gamma that meets the restrictions on the angle θ, but it was decided that this would make the routine unnecessarily complicated. The routine next excluded all gamma rays with θ ≥ π 2 , as for values of θ in this range, the gamma rays are travelling in the negative z direction and so would never reach the detector. It is worth noting that it has been assumed that, should a nucleus decay after the detector and produce a gamma ray travelling in the negative z direction (back towards the detector), that the gamma ray is not recorded should it return and hit the detector. Spherical coordinates can be transformed to their catersian counterparts using the three equations[5] x = −rsinθcosφ , (10) y = rsinθsinφ , (11) z = rcosθ , (12) where the -1 coecient of equation 10 comes from the fact that the x-axis of the detector array is inverted com- pared to the x-axis of the spherical system in which the directions representing the emitted gamma rays path of travel are produced. Equation 12 can be rearranged to give r in terms of z, the distance between the nucleus decay point and the detector, such that r = z cosθ . (13) By substituting this into equations 10 and 11, it is possible to derive equations for the (x, y) coordinates of the gamma ray when level with the detector array, such that x = −ztanθcosφ , (14) y = ztanθsinφ . (15) Using equations 14 and 15, it is straightforward to determine whether the gamma ray hits the detector by checking whether the nal (x, y) coordinates lie within the connes of the detector array. The distribution of gamma rays detected can be seen in gure 9. The result in gure 9 does not account for the nite resolution of the detector array. The resolution of the detector is stated as being 10cm in the x direction and 30cm in the y direction. The eects of the restricted res- olution are modelled by smearing the (x, y) coordinates of each gamma ray detected. This is achieved by adding a random Gaussian distribution term to each of the x and y coordinates, where the standard deviation of each Gaussian term is equal to the resolution of the detector in that direction. The random Gaussian terms were gen- erated using the 'gsl_ran_gaussian' function oered by the GNU Scientic Library. The distribution of gamma rays recorded by the detector, with smearing applied to account for the resolution of the detector, can be seen in gure 10. 5
  • 6. Figure 9: Plot showing the distribution of gamma rays recorded in the detector array, with dimensions of 3m × 3m, in a simulation of the experiment described in Physics Problem 1. 1,000,000 nuclei were present in the simulated beam, of which 854,438 decayed before reaching the detector, with 179,928 actually hitting the detector array. The bin width was 0.1m and the seed of the random number generator was set to zero. Figure 10: Plot showing the distribution of gamma rays recorded in the detector array, with dimensions of 3m × 3m, in a simulation of the experiment described in Physics Problem 1. 1,000,000 nuclei were present in the simulated beam, of which 853,550 decayed before reaching the detector, with 177,067 actually hitting the detector array. The bin width was 0.1m and the seed of the random number generator was set to zero. It is clear from comparing gures 9 and 10 that smear- ing the data to account for the resolution of the detector has tangible eects on the distribution recorded, which manifest themselves as a general broadening of the con- tours in both directions, with this being more prolic in the y direction compared to the x. This is to be ex- pected, as the resolution in the y direction is three times worse than that in the x direction, thus the contours appear elliptical. Because of this, it is evident that the resolution of the detector must be improved in order to accurately represent the distribution of incident gamma rays. In a physical context, a resolution of 30cm, which equates to one tenth the width of the detector itself, is not satisfactory for any genuine nuclear physics applica- tion. References [1] Z. I. B. D. P. Kroese, T. Taimre, Handbook of Monte Carlo Methods (John Wiley Sons, 2011) p. 59. [2] GNU Scientic Library (GSL), 1.13 (http://www.gnu.org/software/gsl) accessed: 20/03/2014. [3] P. L'Ecuyer, Mathematics of Computation 68, 261 (1999). [4] J. H. H. F. Yang, Modern Atomic and Nuclear Physics, revised ed. (World Scientic Publishing Co. Pte. Ltd., 2010) p. 404. [5] B. J. J. E. N. I. Fisher, T. Lewis, Statistical Analysis of Spherical Data, rst paperback ed. (Cambridge University Press, 1993) p. 18.