tw1979 exercise 3 report

6
R 2 x 0 x 1 P (x) P (x) P 0 (x 0 ) x 0 0 x 0 1 P (x) P 0 (x 0 ) x 0 req ˆ x 0 0 P 0 (x 0 )dx 0 = xgen ˆ x0 P (x)dx , x 0 req x gen P (x) x gen x 0 req ˆ x 0 0 P 0 (x 0 )dx 0 = Q(x 0 req ) , Q(x 0 req )= x gen . x 0 req x 0 req = Q -1 (x gen ) . x 0 y 0 y max y max P 0 (x 0 ) x 0 y<P 0 (x 0 ) P 0 (x 0 ) x 0

Upload: thomas-wigg

Post on 18-Aug-2015

105 views

Category:

Documents


1 download

TRANSCRIPT

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 ofrandom number generators. The rst part of the exer-cise required that two dierent methods, the analyticaland 'accept/reject' methods, were used to create a sinu-soidal distribution of random numbers from a uniformdistribution and their eectiveness compared. Whilstboth provided a very good sinusoidal t (with R2 veryclose to one) with a large number of test points, it wasconcluded that the 'accept/reject' method may be moreappropriate generally, as problems can arise with theevalutation and inversion of certain aspects of the an-alytical method. The nal part of the exercise was tomodel 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 usingMonte Carlo techniques. The resolution of the detectorwas also accounted for using Gaussian smearing. It wasconcluded that by applying the smearing, the calculateddistribution became much less precise and less indicativeof the true distribution: the resolution of the detectormust be improved to provide a genuine representation ofthe distribution of counts recorded.

1 Random Numbers in a Distribu-

tion

In general, computational random number generatorsproduce output values within a set range, for instancebetween 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 x′0 andx′1, by each of the following methods.

1.1 Analytical Distribution Transforma-tion

Provided that both P (x) and P ′(x′) are normalised, thecumulative distributions up to the generated values areequivalent, such that

x′reqˆ

x′0

P ′(x′)dx′ =

xgenˆ

x0

P (x)dx , (1)

where x′req is the value which the generated value xgen istransformed into. As P (x) is stated as being a uniformdistribution, the right hand side of equation 1 is simplyequal to xgen. By dening the left hand side of thisequation such that

x′reqˆ

x′0

P ′(x′)dx′ = Q(x′req) , (2)

equation 1 can be simplied to

Q(x′req) = xgen . (3)

It then follows that the equation to obtain x′req cansimply be written

x′req = Q−1(xgen) . (4)

1.2 Accept/Reject Method

This method is similar to the standard Monte Carlomethod of integration[1] and provides another way ofconverting a uniform distribution of generated randomnumbers to an alternative distribution.

First, a uniform random number x′ is generated.Next, another uniform random number y is generated inthe range 0 to ymax, where ymax is greater than, or equalto, the maximum possible value of P ′(x′). The value ofx′ is accepeted if y < P ′(x′), else it is rejected and notrecorded. By this method the distribution P ′(x′) is builtup from the accepted values of x′.

1

Figure 1: Table comparing the performance of many ofthe 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 asecond[2].

1.3 Task 1: Generating Random Anglesin a Sinusoidal Distribution

This task was to generate random angles in the range0 < θ < π using the two methods described in sec-tion 1.1 and 1.2 in distributions that are proportionalto sin(θ). For both methods, a uniform random gen-erator from the GNU Scientic Library (GSL)[2] wasutilised. The GSL libraries oer a selection of randomgenerators and the 'gsl_rng_taus2' generator, a max-imally equidistributed combined Tausworthe generator,was chosen for use in this case. Figure 1 shows the speedof 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 thesame generation algorithm as this but with an improvedseeding procedure[3].

The numbers generator by these GSL-based functionsare 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 thegenerator after the rst repetition and a dierent set ofpseudorandom numbers will be generated. In the caseof this task however, the number of random values re-quired will be much less than 288 so this does not needto 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 wasmost appropriate as the task asked for random angles be-

tween zero and π but not including the two extremetiesof the range.

1.3.1 Transforming to a Sinusoidal DistributionUsing the Analytical Method

As the distribution P ′(x′) is required to be proportionalto sin(θ), the equation for Q(x′req) can be written

Q(x′req) =1

2

x′reqˆ

0

sin(x′)dx′ , (5)

where the 12 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 =

x′reqˆ

0

sin(x′)dx′ (6)

can be derived. Performing the integral and then makingthe required rearrangement, the nal equation

x′req = arccos(1 − 2xgen) , (7)

to nd the sinusoidally distributed random numbers, canbe reached. Equation 7 can simply be entered into theroutine to generate a series of sinusoidally distributedrandom numbers from the uniformly distributed ran-dom numbers generated by the generator function. Thedistrubtions produced by this routine for two dierentnumbers 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 maximalrange of 0 < P ′(x′) < 1. Values of x′ were then gener-ated by simply multiplying the values returned by thegenerator 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 methodwas applied to these values as detailed above. The out-put distributions for a routine utilising the accept/rejectmethod for two dierent numbers of test values can beseen in gures 4 and 5.

1.3.3 Comparing the Analytical and Ac-cept/Reject Methods of Generating aSinusoidal Distribution

It is evident from comparing gures 2 and 4 and gures3 and 5 that the greater the number of random angles

2

Figure 2: Histogram showing the sinusoidal distributionof random angles, x′, in the range 0 < x′ < π, generatedby a program utilising the analytical method of trans-forming a uniform distribution of random numbers. 500angles were generated and the seed for the random num-ber generator was 0. A sinusoidal t has been applied tothe data - the resulting t has an R2 value of 0.78131.

Figure 3: Histogram showing the sinusoidal distributionof random angles, x′, in the range 0 < x′ < π, gen-erated by a program utilising the analytical method oftransforming 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 beenapplied to the data - the resulting t has an R2 value of0.99989.

Figure 4: Histogram showing the sinusoidal distributionof random angles, x′, in the range 0 < x′ < π, gener-ated by a program utilising the 'accept/reject' methodof generating a distribution of random numbers. 808 an-gles were generated, of which 500 were accepted and theseed for the random number generator was 0. A sinu-soidal t has been applied to the data - the resulting thas an R2 value of 0.75930.

Figure 5: Histogram showing the sinusoidal distributionof random angles, x′, in the range 0 < x′ < π, gener-ated by a program utilising the 'accept/reject' method ofgenerating a distribution of random numbers. 1571201angles were generated, of which 1000000 were acceptedand the seed for the random number generator was 0. Asinusoidal t has been applied to the data - the resultingt 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 eachdistribution is to sinusoidal quintitively, a t must be aapplied to the data. This has been done in gures 2to 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 hundredrandomly 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 resultshows that, in this case, the analytical method providesa marginally better sinusoidal distribution than the 'ac-cept/reject' method. However, for such a relatively smallnumber of generated angles, it is not fair to make agenuine comparison between the two methods. For amuch 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. Thesevalues show that both are close to perfect sinusoidal dis-tributions with little deviation from the sinusoidal t. Inthis case again, both distributions displayed very similarR2 values, with the 'accept/reject' method providing amarginally better t this time. The dierence in the R2

values was so minute though, that it is not possible tochoose a preferred method simply from this. Looking atthe other aspects of each method, the analytical methodhas the disadvantage that the denite integral Q(x′req)may sometimes be dicult to evaluate and invert and so,because of its simple nature, the 'accept/reject' methodmay be preferable.

2 Simulations

When modelling physical problems, it is often most ap-propriate to simulate the experimental data point bypoint: this is known as Monte Carlo simulation. Whenit is necessary to model changing or unknowable param-eters, random number generators are used to producethese variables.

2.1 Physics Problem 1: Gamma RayEvents from Unstable NucleiRecorded in a Detector

This nuclear physics experiment to be simulated consistsof a beam of unstable nuclei injected at 2000ms−1 trav-elling in the z direction. The nuclei decay with a meanlifetime of 520µs producing a gamma ray. The producedgamma rays are unpolarised and are therefore emittedisotropically, to be recorded by a detector situated 2mfrom the injection point with a resolution of 10cm inthe x plane and 30cm in the y plane. The experimentalsetup 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 ofthe detector array for the nuclear physics experimentdescribed in Physics Problem 1.

Figure 7: Histogram showing the decay length, or thedistance travelled before decaying, of 1,000,000 nucleiin the beam described in Physics Problem 1 with nodetector 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 emissionin Physics Problem 1.

4

are from the decaying nuclei (no background counts) andthat the nuclei never get scattered before reaching thedetector (all nuclei decay at (x = 0, y = 0, z)). Thenuclei in the beam are subject to the exponential decaylaw[4], which means the rate of decrease in the numberof nuclei is proportional to the number of nuclei at thatpoint in time, such that

dN

dt= −λN (8)

= −Nτ, (9)

where, in the case of this experiment, N is the numberof nuclei left in the beam, λ is the exponential decayconstant and τ is the mean lifetime of the nuclei in thebeam. 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. Figure7 shows the corresponding decay length of the generatedecay times for one million simulated nuclei. As is tobe expected with such a large sample size, the R2 valueof an exponential decay t to the histogram is 0.99999,showing a close to perfect t to the required exponentialdecay 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 pointit reaches the detector. It is assumed that nuclei thatdo not decay before the detector will not produce anygamma rays and do not register as an event in the de-tector. For this reason, the routine excludes any nucleithat are simulated to have a decay length greater thantwo metres. For the nuclei that do decay before reach-ing the detector, the direction in which the gamma rayis emitted is generated randomly in three dimensions bygenerating random values of the polar θ and azimuthalφ angles to give a direction in spherical coordinates. Adiagram of the spherical coordinate system used can beseen in gure 8. φ was generated from a uniform dis-tribution with the range [0, 2π). θ was generated in therange [0, π] but not using a uniform distribution, as thearea element dΩ = sinθdφdθ is a function of θ and wouldtherefore result in more points being generated close tothe poles of the coordinate sphere. To account for this,the values of θ were generated by transforming a uniformdistribution into a sinusoidal distribution using the an-alytical method used in Task 1. The analytical methodwas chosen over the 'accept/reject' method as to avoidthe inevitable loss of data points caused by the natureof the method. This could be avoided using a loop toverify 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 routineunnecessarily complicated.The routine next excluded all gamma rays with θ ≥ π

2 ,

as for values of θ in this range, the gamma rays aretravelling in the negative z direction and so would neverreach the detector. It is worth noting that it has beenassumed that, should a nucleus decay after the detectorand produce a gamma ray travelling in the negative zdirection (back towards the detector), that the gammaray 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 thefact that the x-axis of the detector array is inverted com-pared to the x-axis of the spherical system in which thedirections representing the emitted gamma rays path oftravel are produced.Equation 12 can be rearranged to give r in terms of

z, the distance between the nucleus decay point and thedetector, such that

r =z

cosθ. (13)

By substituting this into equations 10 and 11, it ispossible to derive equations for the (x, y) coordinates ofthe gamma ray when level with the detector array, suchthat

x = −ztanθcosφ , (14)

y = ztanθsinφ . (15)

Using equations 14 and 15, it is straightforward todetermine whether the gamma ray hits the detector bychecking whether the nal (x, y) coordinates lie withinthe connes of the detector array. The distribution ofgamma 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 thedetector is stated as being 10cm in the x direction and30cm in the y direction. The eects of the restricted res-olution are modelled by smearing the (x, y) coordinatesof each gamma ray detected. This is achieved by addinga random Gaussian distribution term to each of the xand y coordinates, where the standard deviation of eachGaussian term is equal to the resolution of the detectorin that direction. The random Gaussian terms were gen-erated using the 'gsl_ran_gaussian' function oered bythe GNU Scientic Library. The distribution of gammarays recorded by the detector, with smearing applied toaccount for the resolution of the detector, can be seen ingure 10.

5

Figure 9: Plot showing the distribution of gammarays recorded in the detector array, with dimensions of3m × 3m, in a simulation of the experiment describedin Physics Problem 1. 1,000,000 nuclei were present inthe simulated beam, of which 854,438 decayed beforereaching the detector, with 179,928 actually hitting thedetector array. The bin width was 0.1m and the seed ofthe random number generator was set to zero.

Figure 10: Plot showing the distribution of gammarays recorded in the detector array, with dimensions of3m × 3m, in a simulation of the experiment describedin Physics Problem 1. 1,000,000 nuclei were present inthe simulated beam, of which 853,550 decayed beforereaching the detector, with 177,067 actually hitting thedetector array. The bin width was 0.1m and the seed ofthe 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 detectorhas tangible eects on the distribution recorded, whichmanifest themselves as a general broadening of the con-tours in both directions, with this being more prolicin the y direction compared to the x. This is to be ex-pected, as the resolution in the y direction is three timesworse than that in the x direction, thus the contoursappear elliptical. Because of this, it is evident that theresolution of the detector must be improved in order toaccurately represent the distribution of incident gammarays. In a physical context, a resolution of 30cm, whichequates to one tenth the width of the detector itself, isnot satisfactory for any genuine nuclear physics applica-tion.

References

[1] Z. I. B. D. P. Kroese, T. Taimre, Handbook of MonteCarlo 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 NuclearPhysics, revised ed. (World Scientic Publishing Co.Pte. Ltd., 2010) p. 404.

[5] B. J. J. E. N. I. Fisher, T. Lewis, Statistical Analysisof Spherical Data, rst paperback ed. (CambridgeUniversity Press, 1993) p. 18.

6