+ All Categories
Home > Documents > Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation...

Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation...

Date post: 28-Mar-2018
Category:
Upload: lekiet
View: 215 times
Download: 3 times
Share this document with a friend
64
Experiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering and Electronics November 9, 2015 Abstract The Monte Carlo method is widely used in simulating and solving real life statistic prob- lems. This report presents the process of utilizing Monte Carlo techniques to analyze the penalty kick in different scenarios, with or without a goalkeeper. Six programming models based on Monte Carlo techniques were established using MATLAB, the results of which were scientifically analyzed. These models were all based on the generation of random num- bers, in the form of either uniform distribution or normal (Gaussian) distribution, which represented the shots. The graphical results of the penalty kick are presented in a specially designed MATLAB GUI window, which contains six functions that represent those six mod- els respectively. The calculated results of the possibility of shooting successfully for different sets of inputs (the number of runs and the number of shots per run) were compared and analysed. In addition, three more models based on normal distribution that were applied differently to the carefully analyzed ones were provided for more comprehensive comparison of the results. Declaration I confirm that I have read and understood the University’s definitions plagiarism and collusion from the Code of Practice on Assessment. I confirm that I have neither commited plagarism in the completion of this work nor have I colluded with any other party in the preparation and production of this work. The work presented here is my own and in my own words except where I have clearly indicated and acknowledged that I have quoted or used figures from published or unpublished source (including the web). I understand the consequences of engaging in plagarism and collusion as described in the Code of Practice on Assessment (Appendix L) 1
Transcript
Page 1: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Experiment 22 - Monte-Carlo Simulation

Student ID: 201139030

Group number: 44

Module code: ELEC273

Department of Electrical Engineering and Electronics

November 9, 2015

Abstract

The Monte Carlo method is widely used in simulating and solving real life statistic prob-lems. This report presents the process of utilizing Monte Carlo techniques to analyze thepenalty kick in different scenarios, with or without a goalkeeper. Six programming modelsbased on Monte Carlo techniques were established using MATLAB, the results of whichwere scientifically analyzed. These models were all based on the generation of random num-bers, in the form of either uniform distribution or normal (Gaussian) distribution, whichrepresented the shots. The graphical results of the penalty kick are presented in a speciallydesigned MATLAB GUI window, which contains six functions that represent those six mod-els respectively. The calculated results of the possibility of shooting successfully for differentsets of inputs (the number of runs and the number of shots per run) were compared andanalysed. In addition, three more models based on normal distribution that were applieddifferently to the carefully analyzed ones were provided for more comprehensive comparisonof the results.

Declaration

I confirm that I have read and understood the University’s definitions plagiarism and collusion from theCode of Practice on Assessment. I confirm that I have neither commited plagarism in the completionof this work nor have I colluded with any other party in the preparation and production of this work.The work presented here is my own and in my own words except where I have clearly indicated andacknowledged that I have quoted or used figures from published or unpublished source (including theweb). I understand the consequences of engaging in plagarism and collusion as described in the Codeof Practice on Assessment (Appendix L)

1

Page 2: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Contents

1 Introduction 11.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Experimental Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.3.1 Analytical Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3.2 The Monte-Carlo Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Materials and Methods 42.1 Apparatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.2 Experimental Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2.1 Model One . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2.2 Model Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2.3 Model Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.4 Model Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.5 Model Five . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.6 Model Six . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2.7 Model Seven, Eight, and Nine . . . . . . . . . . . . . . . . . . . . . . . . . 9

3 Result 103.1 Part One: Without goalkeeper . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3.1.1 Task One . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.1.2 Task Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.1.3 Task Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.1.4 Task Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.1.5 Task Five . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.1.6 Task Six . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.1.7 Task Seven . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.2 Part Two: With goalkeeper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2.1 Task Eight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.2.2 Task Nine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.2.3 Task Ten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4 Discussion and Conclusion 274.1 Objective Achievement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.2 Limitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3 Future Improvement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

5 Review Question 28

6 Reference 32

7 Appendix 337.1 Task 4 and 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337.2 Task 4 and 5 repeated in Task 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . 357.3 Task 4 and 5 repeated in Task 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . 377.4 Model Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.5 GUI Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Page 3: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

1 Introduction

1.1 Background

The Monte Carlo method has wide application in various scientific areas such as finance, t-elecommunications and computer graphics [1]. It is a stochastic technique which is widelyapplied in solving real life problems based on the use of random numbers and probability statis-tics [2]. A typical real life problem, based on statistical analysis discussed in this report is thepenalty kick process, which primarily involves the decision-making of both the goal maker andthe goalkeeper.

In this project, it is assumed that all the shots lie within a circle with a radius of 5 and arectangle with a width of 4 and a height of 2 (as can be seen in Figure 1). The circle representsthe area in which goals can be attempted, and the rectangle represents the area in which goalis shot successfully.

Figure 1: goal arrangement

There are mainly three scenarios: First, there is no goalkeeper; second, the goalkeeper jumpsto different sections of the rectangle with uniform probabilities; third, the goalkeeper tends tojump to the lower two corners with a possibility of 90 percent. The goalkeeper is assumed tohave five possible jump actions as can be seen in Figure 2.

Figure 2: Five possible actions

1

Page 4: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

1.2 Experimental Purpose

The objective of this lab section was mainly to familiarise the experimenters with the workingprinciple of the Monte Carlo technique. This simulation method was expected to be practicedby solving the penalty kick analysis so that the characteristics of this method could be compre-hensively learnt by comparing the results generated based on different type of random numbergenerator (either uniform distribution or normal distribution). Also, the relationship betweenthe number of runs set for the simulation or the number of shots taken in each run of simulationand the result accuracy was required to be discussed as well.

1.3 Theory

1.3.1 Analytical Method

To verify the degree of accuracy of the experimental results worked out using the Monte CarloMethod, analytical method based on mathematic analysis of different scenarios were used toprovide theoretical results as well. The results obtained using simulation should be generallythe same with these theoretical results.

For the senario where random number is in uniform distribution, the corresponding analyt-ical method should be the based on the geometric possibility. This is because in this case, theshoot-out events are regarded as uniform random random distribution, which agrees with theworking conditions of geometric possibility [3].

P =Area of rectangle

Area of circle(1)

For the senario where random number is in normal distribution, particularly indicating thecase where the radius obeys normal distribution while the angle obeys uniform distributionin polar system, the corresponding analytical method should be the integral of the formula ofprobability density based on normal distribution [4].

P (x) =1

σ√

2πe−(x−µ)/(2σ2) (2)

For the senario where random number is in normal distribution, particularly indicating thecase where both the horizontal and vertical axes obey normal distribution in rectangular system,the corresponding analytical method should be the integral of the formula of probability densitybased on normal distribution [5].

P (x) =1

2πσxσy√

1− r2e

12(1−r2)

[(x−µx)2

σx2−2r

(x−µx)(y−µy)σxσy

+(y−µy)2

σy2]

(3)

2

Page 5: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

1.3.2 The Monte-Carlo Method

The Monte Carlo method is a simulation technique for analyzing real life random processesthat involves uncertainty [3]. Generally, the Monte Carlo method is regarded as the kindof technique that applies statistical sampling to solve problems by working out approximatenumerical solutions [4]. It typically solves a statistic problem by generating random numbersin certain type of distribution and observing the numbers that obey some properties [5]. Thismethod is especially useful when numerical solutions to problems which are too complicated tosolve analytically are required.

In this particular project, it is expected to find the sampling distribution of an estimatorof the probability of shooting the goal in a penalty kick using the Mounte Carlo method [1].By replicting the process of picking different samples of the same size (N) out of the totalpopulation for many times (R), several different estimates can be obtained and the calculatedaverage value of them should approximate the real value of the estimator when the estimatetime R is infinitely large [1]. Therefore, practically, this project can be conducted by writingcodes in MATLAB using the following six steps which were summerized based on the workingprinciple of the Monte Carlo technique explained above:

1. A random sample of size N should be drawn based on a random distribution function,where N represents the number of shots for each run of the simulation here in this case.

2. Certain values should be assumed for the parts of the model, where the cooridnates valuesof the points represnting “Miss” and “Shoot” can be distinguished based on which areasthese shots point lie in (the classification of the area was clarified in previous section) inthis case.

3. The parts of the statistic model should be calculated, which means that the number of“Shoot” points should be worked out.

4. The estimate should be calculated, which means that the possibility of shooting success-fully should be worked.

5. The step (1) to (4) should be replicated for R times.

6. The graphical experimental result which represents the distribution of the R times ofestimations should be obtained.

3

Page 6: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

2 Materials and Methods

2.1 Apparatus

The software used here in this project is MATLAB 2013a. The programming simulation modelswere established in the form of “.M” files. Each function represented each model.

In the MATLAB programming environment, totally nine functions were writen (six of whichwere comprehensively analysed and the rest three were simply provided as alternative modelsshowing that the obtained results could vary if the concrete normal distribution method of therandom number is different).

As for the results, the graphical distributions of estimations were presented in the middleof GUI window and the calculated probabilities of shooting successfully were presented in thebottom bar named “P”. Also, the inputs R and N were placed as shown in Figure 3 and sixdifferent scenarios based on different task requirements could be choisen in the top bar named“Type”

Figure 3: MATLAB GUI

4

Page 7: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

2.2 Experimental Procedure

Totally nine computer programmes were written for different scenarios to find the probability ofshooting successfully by simulating N random penalty shots for each estimation and replicatingthis process for R times and calculating the mean of the attempts, where N and R were inputs.

In this section, the core model establishment procedure of each of the nine models willbe briefly introduced with the aid of some screenshots of essential fractions of each program.Detailed codes with comprehensive comments can be seen in Appendix. However, since thebasic establishment principle of different models were the same, the common process can besummerized:

• First, all the related parameters used in the program were clearly declared in the beginninglines as comments (as can be seen in Figure 4).

Figure 4: Parameter

• Then, the goal arrangement area consisting of a circle and a rectangle was drawn.

Figure 5: Draw the areas

• Following that, for uniform random number generator, two “For” loops were used toconduct the concrete simulation: the outer loop was for the parameter experiment time(R) while the inner loop was for the shots number (N). For each experiment (within theinner loop), the shot points coordinates were generated by a uniform random generatoras can be seen in Figure 6.

Figure 6: Random number generator

5

Page 8: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

However, for normal random number generator, the inner “for” loop was replaced by a“while” statement as shown in Figure 7, where C is the number of points lying outsidethe circle and T is the total number of shots generated. In this way, the number of shotswere ensured to be N.

Figure 7: Normal random generator - while loop

• Next, each generated shot was decided by a “if-else” statement and plotted in red andblue dot respectively. Also, points lying in the rectangle were counted to be parameter S.

Figure 8: Plotting

• After the each experiment for N, parameter S was used to calculated possibility of scoringusing formular P0 = S

N . And each P0 was added to the summation P which will be usedto divide by R to obtain the average scoring possibility at the end of the program.

Figure 9: Possibility calculation

After the establishment of the single model, a GUI was created with the aid of blocksprovided by MATLAB itself (the window outlook can be seen in Figure 3 in previous section).

The main section was six models based on 6 possibile combination of uniform/normal gen-erator + without goal keeper/with goalkeeper who kick ball to different areas unformly/withgoalkeeper who tends to kick to lower corner.

Apart from these functions, several GUI modules were created as well: A pushbottumwas a turn-on buttom; the selection bar was to choose from six senarios corresponding todifferent tasks; three text bars were for inputs and output; a axis was used to plotting graphicaldistribution of shots.

The distrinct difference of each model will be introduced as following.

6

Page 9: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

2.2.1 Model One

• Model Description

– This model was written for the situation where there was no goalkeeper using auniform random number generator in the simulation. This model was used in Task2 to Task 6

• Model Establishment

– The uniform random number was generated by multiplying both the angle coordinateand the radius coordinate by a uniform distributed random number from 0 to 1.

Figure 10: Random number generator section

2.2.2 Model Two

• Model Description

– This model was written for the situation where there was no goalkeeper using anormal random number generator in the simulation. This model was used in Task 7.

• Model Establishment

– The normal random number was generated by multiplying both the angle coordinateand the radius coordinate by a normally distributed random number with mean tobe 0 and derivative to be the radius of the circle radius (calculation process of thisradius will be introduced later).

Figure 11: Normal random number generator

7

Page 10: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

2.2.3 Model Three

• Model Description

– This model was written for the situation where there was goalkeeper who protect thegoal in different areas based on uniform distributed random number using a uniformrandom number generator in the simulation. This model was used in Task 8.

• Model Establishment

– The uniform random number was generated using the same code as Model One,while the goalkeeper existence feature added a “switch” statement which generates arandom number from 1,2,3,4,5 uniformly pointing to five different cases correspondingto five different possible actions (Goal arrangement details can be seen in Figure 2).

Figure 12: Switch statement

2.2.4 Model Four

• Model Description

– This model was written for the situation where there was goalkeeper who protect thegoal in different areas based on uniform distributed random number using a normalrandom number generator in the simulation. This model was used in Task 9.

• Model Establishment

– The normal random number generator was the same as Model Two and the “switch”was the same as Model Three.

2.2.5 Model Five

• Model Description

– This model was written for the situation where there was goalkeeper who tend to 90%protect the goal in lower corner, and shots were generated uniformly. This modelwas used in Task 10.

• Model Establishment

– The uniform random number generator was the same as Model One and Three,“switch” cases were the same with Model Three and Four. However, before “switch”statement, the case parameter goalkeeper was classified to two possibilities: if theuniformly generated ramdom number jump is 0 to 0.9, goalkeeper is for the last twocases, otherwise it is for the first three cases.

8

Page 11: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Figure 13: 90% protect lower corner

2.2.6 Model Six

• Model Description

– This model was written for the situation where there was goalkeeper who tend to90% protect the goal in lower corner, and shots were generated normally. This modelwas used in Task 10.

• Model Establishment

– The normal random number generator was the same as Model Two and Four; the“switch” was the same as Model Three, Four and Five; the goalkeeper classificationbefore “switch” statement was the same as Model Five.

2.2.7 Model Seven, Eight, and Nine

• Model Description

– These model was written for the situation based on normal distributed random num-ber but in a slightly different way from Model Two, Four and Six. This normaldistribution was two-dimensional. These three models were not used in any tasksbut simply provided as alternative way of normal distribution.

• Model Establishment

– The normal random number generator can be seen in Figure 16.

Figure 14: two-dimensional normal distribution

– These models were not chosen to be used in Tasks because the generation of randomshots were not quite reasonable. The while loop was used to simply cancel all thepoints outside the circle but in this way, that means all the left points did not quiteagree with normal distribution. However in Model Two, Four and Six, where thenormal districution was only applied on the radius coordinate, the points outsidecircle were less because the distribution was one-dimensional.

9

Page 12: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3 Result

3.1 Part One: Without goalkeeper

3.1.1 Task One

• Result Generation

– As discussed in equation 1 in previous section, when the sttempts are close to infiniteand the penalty taker does not have preference of certain terget area, the possibilityof scoring can be worked out using geomatric possibility principle that is divide areaof rectangle by the area of circle.

To obtain the circle area, the radius was first obtained: As can be seen in Figure1, the radius of circle is half the diagonal (D) of the rectangle since the rectangle isinternally tangent to the circle.

D =√W 2 + L2 =

√42 + 22 = 2

√5 (4)

Therefore the radius is D2 =√

5, and the areas can be worked out:

Acricle = (√

5)2 × π = 5π (5)

Arectangle = W × L = 2× 4 = 8 (6)

Finally, using formula 1, we can obtain the possibility

P =ArectangleAcricle

=8

5π≈ 0.509 (7)

• Result Presentation

– The required numerical value is 0.509.

3.1.2 Task Two

• Result Explaination

– This program has been written as Model One, the detailed code with comments canbe seen in Appendix and a brief explaniation of its eatablishment can be seen inprevious procedure section.

10

Page 13: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3.1.3 Task Three

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Uniform(Without goal-keeper)” which is the scenario for this task. Then, N was input as 1000 and R wasinput as 1. Finally, the “Simulate” buttom was clicked.

• Result Presentation

– The numerical result of the scoring possibility and the graphical result can be seenin Figure 15.

Figure 15: Task3

• Result Explaination

– It can be clearly seen that obtained result 0.496 is quite close to the theoretical resultcalculated in task One. This shows the validity of this program.

11

Page 14: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3.1.4 Task Four

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Uniform(Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=100; R=5, N=1000; R=5,N=10000; R=5, N=100000.

• Result Presentation

– The results are presented in Table 1.

N 100 1000 10000 100000

P 0.492 0.5058 0.51158 0.5088

Table 1: Probability for different N

– The plot of pobability against the value of N is presented in Figure 17.

Figure 16: Task4

12

Page 15: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3.1.5 Task Five

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Uniform(Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=1000; R=10, N=1000; R=15,N=1000; R=20, N=1000.

• Result Presentation

– The results are presented in Table 2.

R 5 10 15 20

P 0.5058 0.5053 0.5068 0.50515

Table 2: Probability for different R

– The numerical results of the scoring possibilities and the graphical results can beseen in Figure 16.

Figure 17: Task5

13

Page 16: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3.1.6 Task Six

• Result Presentation

– For Task 4 where the R remains 5 unchanged while the N increase from 100 to 100000,it can be seen that the larger the N is the closer the result (0.492,0.5058,0.51158,0.5088)is to the theoretical result which is 0.509.

For Task 5 where the N remains 1000 while the R increase from 5 to 20, it can beseen that the larger the R is the result (0.5058,0.5054,0.5068,0.50515) only fluctuatewithin a small range but not necessarily closer to the theoretical result.

• Result Explaination

– This phenonmenon is understandable. First, when experiment times remain the samebut the sample size (the shots number) increases, the simulation will be closer to thereal situation which is a random process, thus the result can be more general that isto say the result is closer to the theoretical result.

However, when the number of shots remain the same only the time of the experimentincrease. The result will be still only for the same size of sample which does notincrease the general value of the result.

Therefore, it can be concluded that by increasing the value of N, the accuracy ofthe result can be improved. If the simulation simulation times is infinite, then theexperimental result can be regarded as equal to the real result. However, if onlyincrease the value of the repeated times of the experiment R, only the precision canbe improved but the accuracy will not be influenced.

3.1.7 Task Seven

Repeat Task 2 in Task 7

• Result Explaination

– This program has been written as Model Two. The detailed code with commentscan be seen in Appendix and a brief explaniation of its eatablishment can be seen inprevious procedure section.

14

Page 17: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 3 in task 7

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal(without goalkeep-er)” which is the scenario for this task. Then, N was input as 1000 and R was inputas 1. Finally, the “Simulate” buttom was clicked.

• Result Presentation

– The numerical result of the scoring possibility and the graphical result can be seenin Figure 18.

Figure 18: Task3

• Result Explaination

– It can be clearly seen that obtained result 0.731 is not quite close to the theoreticalresult calculated in task One. This is because that the normal distribution of randomnumbers is different from the ideal uniform distribution. Normal distribution tendto lie in the center.

15

Page 18: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 4 in Task 7

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal (Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=100; R=5, N=1000; R=5,N=10000; R=5, N=100000.

• Result Presentation

– The results are presented in Table 3.

N 100 1000 10000 100000

P 0.728 0.7454 0.7386 0.7297

Table 3: Probability for different N

– The plot of pobability against the value of N is presented in Figure 19.

Figure 19: Task4

16

Page 19: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 5 in Task 7

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal (Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=1000; R=10, N=1000; R=15,N=1000; R=20, N=1000.

• Result Presentation

– The results are presented in Table 4.

R 5 10 15 20

P 0.74 0.737 0.743 0.736

Table 4: Probability for different R

– The numerical results of the scoring possibilities and the graphical results can beseen in Figure 20.

Figure 20: Task5

17

Page 20: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 6 in Task 7

• Result Presentation

– For Task 4 where the R remains 5 unchanged while the N increase from 100 to 100000,it can be seen that the larger the N is, the result (0.728,0.7454,0.7386,0.7297) is closerto a certain value which is approximately 0.73.

For Task 5 where the N remains 1000 while the R increase from 5 to 20, it can beseen that the larger the R is the result (0.74,0.737,0.743,0.736 ) only fluctuate withina small range but not necessarily close to a result.

• Result Explaination

– As has been discussed in previous section, the conclusion of “Large N increase theaccuracy” should be correct. Therefore the value 0.7297 should be the closest to thetheoretical value for this situation. The actual value of this theoretical result wasnot calculated because this project focuses on the Monte Carlo method rather thanmath and we have already drawn the conclusion previously so that we can inducethat the theoretical result might be 7.3.

Also, it can be found that the possibility of scoring when the normal random numbergenerator is used larger than that when the uniform random number generator isused. This is because the normal distribution make numbers accumulate in thecenter, which means there are more shots lying in the central rectangle area so thatthe possibility of scoring increases.

3.2 Part Two: With goalkeeper

3.2.1 Task Eight

For N=100 and N=1000, the results are presented in figure below.

Figure 21: Task8

18

Page 21: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 1

• Result Generation

– As discussed in equation 1 in previous section, when the sttempts are close to infiniteand the penalty taker does not have preference of certain terget area, the possibilityof scoring can be worked out using geomatric possibility principle.

When the possibility of jumping to 5 different areas shown in Figure 2 are the same,it can be expressed that P1 = P2 = P3 = P4 = P5 = 0.2. For the first case, thepossibility of scoring in that scenario is

AsamllrectAcircle

where “small rect” refers to theun-shadowed rectangule(s) area.

P = (P1 ×1

2×Arectangle + P2 ×

3

4×Arectangle × 4)/Acircle (8)

Substituting Arectangle=8, and Acircle = 5π, therefore we could obtain P ≈ 0.3565.

• Result Presentation

– The required numerical value is 0.3565.

Compare to Task 3

• Result Presentation

– The results of Model 3 and Model 1 when N=1000 can be seen in Figure 22.

Figure 22: Task3

• Result Explaination

– It can be clearly seen that the possibility of scoring when with goalkeeper is appar-ently smaller than that when without goalkeeper (0.368<0.496). Therefore, it canbe concluded that the possibility of scoring has decreased due to the existence of thegoalkeeper. Most of the shots that lie in the rectangle area get score, which is thesame as the real life situation for a kenalty kick.

19

Page 22: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3.2.2 Task Nine

Compare to Task 3

• Result Presentation

– For N=100 and N=1000, the results are presented in figure below.

Figure 23: Task9

• Result Explaination

– It can be clearly seen that the possibility of scoring when with goalkeeper is relativelysmaller than that when without goalkeeper (0.464<0.496).

However, compared to the possibility obtained in scenario of uniform distributionsof shots, when shots are normally distributed, the effectivity of goalkeeper is less(0.464>0.368).

This means that it is easier to shoot successfully when the shots obey random dis-tribution.

Repeat Task 2 in Task 9

• Result Explaination

– This program has been written as Model Four. The detailed code with commentscan be seen in Appendix and a brief explaniation of its eatablishment can be seen inprevious procedure section.

20

Page 23: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 3 in Task 9

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal(goalkeeper withuniform action)” which is the scenario for this task. Then, N was input as 1000 andR was input as 1. Finally, the “Simulate” buttom was clicked.

• Result Presentation

– The numerical result of the scoring possibility and the graphical result can be seenin Figure 24.

Figure 24: Task3

• Result Explaination

– It can be clearly seen that obtained result 0.491 is not quite close to the theoreticalresult calculated in task One repeated in Task 8 which was 0.3565. This is becausenormal distribution tend to lie in the center. Therefore, it can be concluded that theprobability of scoring has decreased because of the normal distribution of randomnumbers since there are more points in the center (rectangle), but it is still smallerthan situation when there is no goalkeeper.

21

Page 24: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 4 in Task 9

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal (Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=100; R=5, N=1000; R=5,N=10000; R=5, N=100000.

• Result Presentation

– The results are presented in Table 5.

N 100 1000 10000 100000

P 0.486 0.4608 0.47332 0.4706

Table 5: Probability for different N

– The plot of pobability against the value of N is presented in Figure 25.

Figure 25: Task4

22

Page 25: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 5 in Task 9

• Result Generation

– The “Type” choice in GUI window was first chosen to be “Normal (Without goal-keeper)” which is the scenario for this task. Then, four experiment were conductedfor input sets: R=5, N=1000; R=10, N=1000; R=15,N=1000; R=20, N=1000.

• Result Presentation

– The results are presented in Table 6.

R 5 10 15 20

P 0.4796 0.5157 0.4732 0.47015

Table 6: Probability for different R

– The numerical results of the scoring possibilities and the graphical results can beseen in Figure 26.

Figure 26: Task5

23

Page 26: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Repeat Task 6 in Task 9

• Result Presentation

– As has been discussed for previous scenarios based on either uniform random numbergenerator or normal random number generator, the conclusion of “The larger the Nis the more accurate the result is” is still valid.

• Result Explaination

– The only difference between this scenario and the previous two discussed scenariosin task 6 is the existence of goalkeeper which only decrease the possibility of scoringbut makes the validified property of sampling and simulation remain the same.

Compare Task 9 with Task 7

• Result Presentation

– The results of task 9 and task 7 are presented in Table 7 and 8.

N 100 1000 10000 100000

P(Task9) 0.486 0.4608 0.47332 0.4706P(Task7) 0.728 0.7454 0.7386 0.7297

Table 7: Probability for different N

R 5 10 15 20

P(Task9) 0.5058 0.5053 0.5068 0.50515P(Task7) 0.74 0.737 0.743 0.736

Table 8: Probability for different R

• Result Explaination

– For Model Four and Model Two, the only difference is the existence of the goalkeeper,it can be seen clearly that no matter changing the R or N, the possibility of scoringwith a goalkeeper is always less than that without a goalkeeper which is consistentwith the real life situation.

24

Page 27: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Compare Task 9 with Task 8

• Result Presentation

– The results of task 9 and task 8 when N=1000, R=1 are presented in Table 9.

Possibility Possibility

P(Task9) 0.5058P(Task8) 0.368

Table 9: Probability for different R

• Result Explaination

– It can be seen that the possibility of scoring is larger when based on normal randomnumber generator. this is because normal distribution makes more shots lie in thecentral thus lie in the rectangle.

3.2.3 Task Ten

• Result Presentation

– For N=100 and N=1000 when uniform random number generator is used, the resultsare presented in figure below.

Figure 27: Task10

25

Page 28: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

– For N=100 and N=1000 when normal random number generator is used, the resultsare presented in figure below.

Figure 28: Task10

• Result Explainnation

– It can be seen that the when the goalkeeper tends to jump to the lower two corners,the probability of scoring in scenarios based on random number generator either inthe form of uniform or narmal under normal increases (0.371>0.368;0.546>0.491)compared to when goalkeeper does not have preference of action.

– This is because as shown in Figure 2, only for the first case can goalkeeper protect halfof the rectangle while for the rest of the four cases, the possibility of the goalkeeperprotecting the goal successfully is less. However, since the goalkeeper tends to jumpto lower corners rather than jump in the case one, the success possibility of thegoalkeeper is naturally less, thus the possibility of scoring increases.

26

Page 29: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

4 Discussion and Conclusion

4.1 Objective Achievement

The main achievements of this lab section are that the objectives of this project were fullfilled:

First, the Monte Carlo method working priciple that utilizing repeated sampling experimentsbased on random number generator to solve real life questions was comprehensively learnt bysearching for explainations and reading the lab report. It is essential to get farmiliar with thistechnique since this simulation method has wide use in science.

Also, this technique was practiced on penalty kick queation for six different scenarios andthe six program models established coorresponding to them were tested by conducting ten tasksas discussed in previous sections.

Additionally, several usefull conclusions related to the Monte Carlo method were otainedsuch as the bigger the sample size is, the closer the experimental results of the simulation areto the theoratical result.

4.2 Limitation

However, there are some limitations existing in the process of conducting the lab section as well:

First, for the experimental results obtained based on either uniform random number genera-tor or normal random number generator, they were not 100 percent the same as the theoreticalresults when the sample (N) is not large enough. This can be seen as systematic error which isintrinsic to this method.

Second, to obtain more accurate result, we set N=100000 and R=5 for some tasks, but thegraphical result in GUI could not be generated due to the computer function limitation, andeven when the Model was run by itself it took more than ten minutes to simulate which wasnot efficient.

4.3 Future Improvement

For the normal random number generator, more accurate theoretical results calculated basedon the equation 2 and 3 provided would be helpfull to draw to the comclusion of “the largerthe sample is, the accurate the resultis” more comprehensively. However, this can be seen astrade-off as well: the exact random number distribution we applied here was not strict simpledistribution which means that apart from the equation 2 and3, more advanced mathematicaltechniques would be necessary to work out the theoretical result; on the other hand, one distinctadvantage of this Monte Carlo method is that it allow users to stop using those complicatedmath techniques to calculate results using analytical method.

27

Page 30: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

5 Review Question

1. In terms of what youve done in this mini-project, comment on the advantagesand disadvantages (or drawbacks) of the Monte Carlo experiment.

Answer:

• Advantage

– Flexibility: It allows for infinite runs of estimations for different samples of thesame size from the original population when finding the sampling distributionof an estimator, which means that it is fairly flexible by setting no limitation tothe scope of analysis.

– Understandability: Unlike other mathematics-based analysis methods, anotheradvantage of the Monte-Carlo method is that it can be easily applied by follow-ing several fixed operating steps, which enable non-mathematicians to utilize iteasily.

– Practicality: The application of the Monte Carlo method has close relevance tovarious fields such as computer graphics and telecommunications, which illus-trates its wide practicality in the scientific area.

• Disadvantahe

– Experimental Error: The results obtained using this simulation method werenot 100 percent the same as the theoretical results. This is due to the fact thatduring the experiment process, it was found that the produced random numbers,either in the form of uniform numbers or normal numbers, were not actually realuniform/normal random numbers, which introduced a degree of experimentalerror to the results.

– Deterministic Simulation: Inputs such as assumed mean and standard deviationthat affect the outcome can be assigned by the users, which allows extensivedeterministic simulations according to different requirements. However, qualityinputs are required to obtain quality outputs. To what extent should the usersset the inputs is difficult to decide.

28

Page 31: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

2. Discuss the ways in which the above model could be made more accurate andrealistic.

Answer:

First, the goal arrangement should be ameliorated by taking the realistic situation intoaccount: the round circle of the possible shooting area is actually excessively large, sinceit is impossible to shoot into the lower crescent shaped area below the rectangle with thelower line of the rectangle representing the ground.

Figure 29: More realistic model

Second, the division of areas and the cases of the action the goalkeeper may take as shownin Figure 2 is too simplified. It is recommended that smaller rectangles should be dividedand more cases of goalkeeper action should be classified.

Third, the ball itself has a volumn, in this project we assumed it to be simplify a pointwhich is fairly idead and impossibile in real life. Therefore, it is recommended that wetake the ball volumn into consideration and make more carful analysis for situations whenthe ball lie on the edge of the circle.

Fourth, the assumption that the circle area is the total area where all the possibile shot-s may lie in may not be realistic enough. More reasonable total area arrangement isrecommended to be found out based on statistic study.

29

Page 32: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

3. With reference to Task-7 and Task-9, discuss the effect of changing the stan-dard deviation of the Guassian distribution on both the accuracy and precisionof the penalty shots.

Answer:

Based on the normal distribution characteristics, it is known that the larger the standarddeviation is, the more numbers accumulate into the central (as can be seen in Figure 30).

Mathematically, this deviation only influences the precison (the precision increases withthe increase of the standard deviation).

Figure 30: Effect of standard deviation difference

However, in this particular project, the accuracy also increases with the increase of thestandard deviation. This is because if we adopt a sigma smaller than

√5, we would obtain

a larger possibility of scoring.

30

Page 33: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

4. In a large number of balls are kicked on the goal (i.e. if N is sufficientlylarge), the value of π can be estimated using (some function of) the ratio ofthe number of scores to the total number of the shots. Hence, find the relationthat estimates the value of π. Verify this using your results for both uniformand Gaussian distributions.

Answer:

In theory, the possibility of scoring is P =ArectangleAcircle

= 85π . Since when N is quite large the

experimentally generated simulation result should be quiee close to the theoretical result,we can conduct the approximation that

8

5π= 0.5088 (9)

Where the 0.5088 is the experimental result of the possibility of scoring based in uniformrandom number generator when N=100000.

Then, it can be calculated that π ≈ 3.145, which is quite close to the real result. Thisis because the ideal condition where we work out the theoretical result of the scoringpossibility using geometric principle is under the approximation that infinite number ofshots are uniformly randomly distributed. That is to say, the uniform random numbergenerator case is more consistent with the ideal situation.

However, when we substitute the possibility of scoring based in uniform random numbergenerator when N=100000,

8

5π= 0.7297 (10)

then the calculated π ≈ 2.193 is not quite close to the real result. This is because thenormal distribution is a process of random number generation which is closer to real lifesituation rather than ideal situation as used in Task 1.

5. From our observation and results of Part II, what is the best strategy thatshould be adopted by the penalty taker? What is the best strategy that shouldbe adopted by the goalkeeper?

Answer:

The penalty taker is recommended to adopt the action method of shooting the upper leftcorner and the upper right corner since statistically 90 percent of the time goalkeeperstend to jump to the two lower corners of the goal.

However, for the goalkeeper, it is recommended that he/she should protect the goal asusing the action shown in case one (the goal arrangement can be seen in Figure 2).

This is because firstly, when shots are distributed uniformly, in that case, the largestarea can be protected compared with the rest four cases (First case allows the goalkeeperprotecting half the area of the rectangle while the rest four only allow a quater); secondly,when shots are distributed normally, the shots tend to lie in the middle of the rectanglewhich is right area being protected in the case one.

31

Page 34: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

6 Reference

1 University of Liverpool, ”Monte Carlo Simulation script”,Ver 3.3, Aug, 2015

2 Joy Woller. (1996). The Basics of Monte Carlo Simulations [Online]. Available FTP:http://www.cs.cornell.edu/jwoller/samples/montecarlo/

3 (2015). Monte Carlo Simulation - Tutorial [Online]. Available FTP: http://www.solver.com/monte-carlo-simulation-tutorial

4 (2015). What is the Monte Carlo method [Online]. Available FTP: http://www.goldsim.com/Web/Introduction/Probabilistic/MonteCarlo/

5 Joy Woller. (1996). The Basics of Monte Carlo Simulations [Online]. Available FTP:http://mathworld.wolfram.com/NormalDistribution.html

32

Page 35: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

7 Appendix

7.1 Task 4 and 5

• Task 4: The numerical results of the scoring possibilities and the graphical results can beseen in Figure 30.

Figure 31: Task4

33

Page 36: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

• Task 5: The numerical results of the scoring possibilities and the graphical results can beseen in Figure 31.

Figure 32: Task5

34

Page 37: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

7.2 Task 4 and 5 repeated in Task 7

• Task 4: The numerical result of the scoring possibility nd the graphical result whenN=1000, R=1 a can be seen in Figure 32.

Figure 33: Task5

35

Page 38: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

• Task 5: The numerical result of the scoring possibility nd the graphical result whenN=1000, R=1 a can be seen in Figure 33.

Figure 34: Task5

36

Page 39: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

7.3 Task 4 and 5 repeated in Task 9

• Task 4: The numerical result of the scoring possibility nd the graphical result whenN=1000, R=1 a can be seen in Figure 34.

Figure 35: Task5

37

Page 40: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

• Task 5: The numerical result of the scoring possibility nd the graphical result whenN=1000, R=1 a can be seen in Figure 35.

Figure 36: Task5

38

Page 41: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

7.4 Model Code

• Model One

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function [Result]=PartOneUniform(N,R)P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0; %Initialize the S for each estimation

for N=1:Nr=sqrt(5)*sqrt(rand()); %Uniform random generators of thea=2*pi*rand(); %radius and the angle

x=cos(a)*r; %Convert the polar coordinates toy=sin(a)*r; %the rectangular coordinates

if (abs(x)<2&&abs(y)<1) %Count the number of ``Shoot" andS=S+1; %plot themShoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob'); %Plot the points of ``Miss"hold onendend

PO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartOneUniform'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');axis equalend

Result=P/R; %Calculate the average possibilty

39

Page 42: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

• Model Two

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function [Result]=PartOneNormal(N,R)P=0; %Initialize the Prect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold onfor R=1:RT=0; %Total shotsC=0; %points lying outside the circleS=0; %Initialize the S for each estimation

while (T-C<N) %Ensure N shots in circler=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if (xˆ2+yˆ2>5) %Count the points outside circleC=C+1;elseif (abs(x)<2&&abs(y)<1) %Count the number of ``Shoot" andS=S+1; %plot themShoot=plot(x,y,'+r');hold onelse %Plot the points of ``Miss"Miss=plot(x,y,'ob');hold onendendT=T+1;endPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartOneNormal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');end

Result=P/R; %Calculate the average possibilty

40

Page 43: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

• Model Three

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function [Result]=PartTwoUniform(N,R)P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0; %Initialize the S for each estimationfor N=1:Nr=sqrt(5)*sqrt(rand()); %Uniform random generators of thea=2*pi*rand(); %radius and the angle

x=cos(a)*r; %Convert the polar coordinates toy=sin(a)*r; %the rectangular coordinates

goalkeeper=round(rand()*5+0.5); %Case 1,2,3,4,5 has uniform possibilityswitch(goalkeeper)case{1}if (abs(x)>1&&abs(x)<2&&abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0&&x<2&&abs(y)<1)||(x>-1 && x<0 && y<1 && y>0)||(x>-2&&x<-1&&y<0&&y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2&&x<0&&abs(y)<1)||(x>0&&x<1&&y>0&&y<1)||(x>1&&x<2&&y<0&&y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onend

41

Page 44: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

case {4}if ((x>-2&&x<0&&y<1&&y>0)||(x>0&&x<2&&abs(y)<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1&&x<=0&&x>-2)||(x>=0&&x<2&&y>=0&&y<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendend

PO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartTwoUniform'); %Present axes name, title and legendxlabel('x');ylabel('y');axis equallegend([Shoot,Miss],'Score','Miss');end

Result=P/R; %Calculate the average possibilty

• Model Four

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function[Result]=PartTwoNormal(N,R)P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RT=0; %Total shotsS=0; %Initialize the S for each estimation

42

Page 45: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

C=0; %points lying outside the circle

while (T-C<N) %Ensure N shots in circler=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if ((xˆ2+yˆ2)>5) %Count the points outside circleC=C+1;else %Case 1,2,3,4,5 has uniform possibilitygoalkeeper=round(rand()*5+0.5);switch (goalkeeper)case {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendend

43

Page 46: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

T=T+1; %Count the total shots generatedendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilitiesend

title('PartTwoNormal'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');

Result=P/R; %Calculate the average possibilty

• Model Five

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function[Result]=PartTwo10Uniform(N,R)P=0; %Initialize the P

sect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(sect(1,:),sect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0; %Initialize the S for each estimationfor N=1:Nr=sqrt(5)*sqrt(rand()); %Uniform random generators of thea=2*pi*rand(); %radius and the angle

x=cos(a)*r; %Convert the polar coordinates toy=sin(a)*r; %the rectangular coordinates

jump=rand(); %possibility of action from 0 to 1if jump<=0.9 %90% protect the lower cornergoalkeeper=round(rand()+4);elsegoalkeeper=round(rand()*3+0.5);endswitch (goalkeeper) %Five cases of goalkeeper actioncase {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;h1=plot(x,y,'+r');hold onelseh2=plot(x,y,'ob');

44

Page 47: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartTwo10Uniform(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');axis equallegend([h1,h2],'Score','Miss');end

Result=P/R; %Calculate the average possibilty

• Model Six

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation

45

Page 48: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function[Result]=PartTwo10Normal(N,R)P=0; %Initialize the P

sect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(sect(1,:),sect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RT=0; %Total shotsS=0; %Initialize the S for each estimationC=0; %points lying outside the circlewhile (T-C<N)r=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if ((xˆ2+yˆ2)>5) %Count the points outside circleC=C+1;elsejump=rand(); %possibility of action from 0 to 1if jump<=0.9 %90% protect the lower cornergoalkeeper=round(rand()+4);elsegoalkeeper=round(rand()*3+0.5);endswitch (goalkeeper) %Five cases of goalkeeper actioncase {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');

46

Page 49: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendendendT=T+1;endPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilitiesend

title('PartTwo10Normal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');

Result=P/R; %Calculate the average possibilty

• Model Seven

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function [Result] = PartOneNormal2(N,R)P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:R

47

Page 50: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

S=0;for N=1:Nx=normrnd(0,sqrt(5)); %Generate shots based on 2-D normaly=normrnd(0,sqrt(5)); %distribution

while (xˆ2+yˆ2>5) %Cancel the points outside the circlex=normrnd(0,sqrt(5));y=normrnd(0,sqrt(5));endif (abs(x)<2&&abs(y)<1) %Count the number of ``Shoot" andS=S+1; %plot themShoot=plot(x,y,'+r');hold onelse %Plot the points of ``Miss"Miss=plot(x,y,'ob');hold onendendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilitiesend

title('PartOneNormal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');

Result=P/R; %Calculate the average possibilty

• Model Eight

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function[Result]=PartTwoNormal2(N,R)P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0;for N=1:Nx=normrnd(0,sqrt(5)); %Generate shots based on 2-D normaly=normrnd(0,sqrt(5)); %distribution

while (xˆ2+yˆ2>5) %Cancel the points outside the circle

48

Page 51: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

x=normrnd(0,sqrt(5));y=normrnd(0,sqrt(5));endgoalkeeper=round(rand()*5+0.5); %Case 1,2,3,4,5 has uniform possibilityswitch (goalkeeper)case {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartTwoNormal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');axis equallegend([Shoot,Miss],'Score','Miss');end

49

Page 52: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Result=P/R; %Calculate the average possibilty

• Model Nine

%************************* Parameter Notation ******************************%P: Sum of the possibilities of shooting successfully%P0: Possibility of shooting in the goal successfully in each simulation%R: Number of runs of the simulation%N: Number of shots in each run of the simulation%S: Number of shots that are shot in successfully in each simulation%r: The radius coordinate of each point%a: The angle coordinate of each point%x: The horizontal coordinate of each point%y: The vertical coordinate of each point%***************************************************************************

function[Result]=PartTwo10Normal2(N,R)P=0; %Initialize the Psect=[-2,-2,2,2,-2;-1,1,1,-1,-1];plot(sect(1,:),sect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold onfor R=1:RS=0; %Initialize the S for each estimationfor N=1:Nx=normrnd(0,sqrt(5)); %Generate shots based on 2-D normaly=normrnd(0,sqrt(5)); %distribution

while (xˆ2+yˆ2>5) %Cancel the points outside the circlex=normrnd(0,sqrt(5));y=normrnd(0,sqrt(5));endjump=rand; %possibility of action from 0 to 1if jump<=0.9 %90% protect the lower cornergoalkeeper=round(rand()+4);elsegoalkeeper=round(rand()*3+0.5);endswitch (goalkeeper) %Five cases of goalkeeper actioncase {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');endcase{3}

50

Page 53: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendendendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartTwo10Normal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');axis equallegend([Shoot,Miss],'Score','Miss');end

Result=P/R; %Calculate the average possibilty

7.5 GUI Code

function varargout = trailgui(varargin)% TRAILGUI MATLAB code for trailgui.fig% TRAILGUI, by itself, creates a new TRAILGUI or raises the existing% singleton*.%% H = TRAILGUI returns the handle to a new TRAILGUI or the handle to% the existing singleton*.%% TRAILGUI('CALLBACK',hObject,eventData,handles,...) calls the local% function named CALLBACK in TRAILGUI.M with the given input arguments.%% TRAILGUI('Property','Value',...) creates a new TRAILGUI or raises the% existing singleton*. Starting from the left, property value pairs are% applied to the GUI before trailgui OpeningFcn gets called. An% unrecognized property name or invalid value makes property application% stop. All inputs are passed to trailgui OpeningFcn via varargin.

51

Page 54: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

%% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one% instance to run (singleton)".%% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help trailgui

% Last Modified by GUIDE v2.5 04-Nov-2015 23:21:59

% Begin initialization code - DO NOT EDITgui Singleton = 1;gui State = struct('gui Name', mfilename, ...'gui Singleton', gui Singleton, ...'gui OpeningFcn', @trailgui OpeningFcn, ...'gui OutputFcn', @trailgui OutputFcn, ...'gui LayoutFcn', [] , ...'gui Callback', []);if nargin && ischar(varargin{1})gui State.gui Callback = str2func(varargin{1});end

if nargout[varargout{1:nargout}] = gui mainfcn(gui State, varargin{:});elsegui mainfcn(gui State, varargin{:});end% End initialization code - DO NOT EDIT

% --- Executes just before trailgui is made visible.function trailgui OpeningFcn(hObject, eventdata, handles, varargin)% This function has no output args, see OutputFcn.% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)% varargin command line arguments to trailgui (see VARARGIN)

% Choose default command line output for trailguihandles.output = hObject;

% Update handles structureguidata(hObject, handles);

% UIWAIT makes trailgui wait for user response (see UIRESUME)% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.function varargout = trailgui OutputFcn(hObject, eventdata, handles)% varargout cell array for returning output args (see VARARGOUT);% hObject handle to figure% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structurevarargout{1} = handles.output;

% --- Executes on button press in pushbutton1.

52

Page 55: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

function pushbutton1 Callback(hObject, eventdata, handles)% hObject handle to pushbutton1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)switch get(handles.popupmenu1,'Value')case 1Uniform without goalkeeper(handles);case 2Normal without goalkeeper(handles);case 3Uniform with goalkeeper(handles);case 4Normal with goalkeeper(handles);case 5Uniform with goalkeeper 90(handles);case 6Normal with goalkeeper 90(handles);otherwiseend

function edit1 Callback(hObject, eventdata, handles)% hObject handle to edit1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text% str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.function edit1 CreateFcn(hObject, eventdata, handles)% hObject handle to edit1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end

function Normal without goalkeeper(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0; %Initialize the Prect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold onfor R=1:RT=0; %Total shotsC=0; %points lying outside the circleS=0; %Initialize the S for each estimation

while (T-C<N) %Ensure N shots in circler=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

53

Page 56: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if (xˆ2+yˆ2>5) %Count the points outside circleC=C+1;elseif (abs(x)<2&&abs(y)<1) %Count the number of ``Shoot" andS=S+1; %plot themShoot=plot(x,y,'+r');hold onelse %Plot the points of ``Miss"Miss=plot(x,y,'ob');hold onendendT=T+1;endPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartOneNormal(ZHAO)'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');end

Result=P/R; %Calculate the average possibiltyset(handles.edit3,'String',num2str(Result));

function Uniform without goalkeeper(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0; %Initialize the S for each estimation

for N=1:Nr=sqrt(5)*sqrt(rand()); %Uniform random generators of thea=2*pi*rand(); %radius and the angle

x=cos(a)*r; %Convert the polar coordinates toy=sin(a)*r; %the rectangular coordinates

if (abs(x)<2&&abs(y)<1) %Count the number of ``Shoot" andS=S+1; %plot themShoot=plot(x,y,'+r');hold onelse

54

Page 57: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

Miss=plot(x,y,'ob'); %Plot the points of ``Miss"hold onendend

PO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartOneUniform'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');axis equalend

Result=P/R; %Calculate the average possibiltyset(handles.edit3,'String',num2str(Result));

function Normal with goalkeeper(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RT=0; %Total shotsS=0; %Initialize the S for each estimationC=0; %points lying outside the circle

while (T-C<N) %Ensure N shots in circler=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if ((xˆ2+yˆ2)>5) %Count the points outside circleC=C+1;else %Case 1,2,3,4,5 has uniform possibilitygoalkeeper=round(rand()*5+0.5);switch (goalkeeper)case {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))

55

Page 58: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendendT=T+1; %Count the total shots generatedendPO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilitiesend

title('PartTwoNormal'); %Present axes name, title and legendxlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');

Result=P/R; %Calculate the average possibiltyset(handles.edit3,'String',num2str(Result));

function Uniform with goalkeeper(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0; %Initialize the P

rect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(rect(1,:),rect(2,:),'k')

56

Page 59: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RS=0; %Initialize the S for each estimationfor N=1:Nr=sqrt(5)*sqrt(rand()); %Uniform random generators of thea=2*pi*rand(); %radius and the angle

x=cos(a)*r; %Convert the polar coordinates toy=sin(a)*r; %the rectangular coordinates

goalkeeper=round(rand()*5+0.5); %Case 1,2,3,4,5 has uniform possibilityswitch(goalkeeper)case{1}if (abs(x)>1&&abs(x)<2&&abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0&&x<2&&abs(y)<1)||(x>-1 && x<0 && y<1 && y>0)||(x>-2&&x<-1&&y<0&&y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2&&x<0&&abs(y)<1)||(x>0&&x<1&&y>0&&y<1)||(x>1&&x<2&&y<0&&y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2&&x<0&&y<1&&y>0)||(x>0&&x<2&&abs(y)<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1&&x<=0&&x>-2)||(x>=0&&x<2&&y>=0&&y<1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendend

57

Page 60: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

end

PO=S/N; %Calculate the shooting possibilityP=P+PO; %Sum up the possibilities

title('PartTwoUniform'); %Present axes name, title and legendxlabel('x');ylabel('y');axis equallegend([Shoot,Miss],'Score','Miss');end

Result=P/R; %Calculate the average possibiltyset(handles.edit3,'String',num2str(Result));

function Normal with goalkeeper 90(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0; %Initialize the P

sect=[-2,-2,2,2,-2;-1,1,1,-1,-1]; %Draw the rectangle and cirleplot(sect(1,:),sect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

for R=1:RT=0; %Total shotsS=0; %Initialize the S for each estimationC=0; %points lying outside the circlewhile (T-C<N)r=normrnd(0,sqrt(5)); %Normal random generators of thea=2*pi*rand(); %radius and the angle

x=r*cos(a); %Convert the polar coordinates toy=r*sin(a); %the rectangular coordinates

if ((xˆ2+yˆ2)>5)C=C+1;elsejump=rand;if jump<=0.9goalkeeper=round(rand()+4);elsegoalkeeper=round(rand()*3+0.5);endswitch (goalkeeper)case {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))

58

Page 61: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;Shoot=plot(x,y,'+r');hold onelseMiss=plot(x,y,'ob');hold onendendendT=T+1;endPO=S/N;P=P+PO;end

title('PartTwo10Normal(ZHAO)');xlabel('x');ylabel('y');legend([Shoot,Miss],'Score','Miss');

Result=P/R;set(handles.edit3,'String',num2str(Result));

function Uniform with goalkeeper 90(handles)N=get(handles.edit1,'string');N=str2double(N);R=get(handles.edit2,'string');R=str2double(R);P=0;sect=[-2,-2,2,2,-2;-1,1,1,-1,-1];plot(sect(1,:),sect(2,:),'k')hold onezplot('xˆ2+yˆ2=5')hold on

59

Page 62: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

for i=1:RS=0;for j=1:Nr=sqrt(5)*sqrt(rand());a=2*pi*rand();x=cos(a)*r;y=sin(a)*r;jump=rand;if jump<=0.9goalkeeper=round(rand()+4);elsegoalkeeper=round(rand()*3+0.5);endswitch (goalkeeper)case {1}if (abs(x)>1 && abs(x)<2 && abs(y)<1)S=S+1;h1=plot(x,y,'+r');hold onelseh2=plot(x,y,'ob');hold onendcase {2}if ((x>0 && x<2 && abs(y)<1) | | (x>-1 && x<0 && y<1 && y>0) | | (x>-2 && x<-1 && y<0 && y>-1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');endcase{3}if ((x>-2 && x<0 && abs(y)<1) | | (x>0 && x<1 && y>0 && y<1) | | (x>1 && x<2 && y<0 && y>-1))S=S+1;plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase {4}if ((x>-2 && x<0 && y<1 && y>0) | | (x>0 && x<2 && abs(y)<1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendcase{5}if ((abs(y)<1 && x<=0 && x>-2) | | (x>=0 && x<2 && y>=0 &&y<1))S=S+1;h1=plot(x,y,'+r');hold onelseplot(x,y,'ob');hold onendendend

60

Page 63: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

title('PartTwo10Uniform');xlabel('x');ylabel('y');PO=S/N;axis equalP=P+PO;legend([h1,h2],'Score','Miss');endResult=P/R;set(handles.edit3,'String',num2str(Result));

function edit2 Callback(hObject, eventdata, handles)% hObject handle to edit2 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text% str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.function edit2 CreateFcn(hObject, eventdata, handles)% hObject handle to edit2 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end

% --- Executes on selection change in popupmenu1.function popupmenu1 Callback(hObject, eventdata, handles)% hObject handle to popupmenu1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array% contents{get(hObject,'Value')} returns selected item from popupmenu1

% --- Executes during object creation, after setting all properties.function popupmenu1 CreateFcn(hObject, eventdata, handles)% hObject handle to popupmenu1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end

% --- Executes on button press in checkbox1.function checkbox1 Callback(hObject, eventdata, handles)% hObject handle to checkbox1 (see GCBO)

61

Page 64: Experiment 22 - Monte-Carlo Simulation · PDF fileExperiment 22 - Monte-Carlo Simulation Student ID: 201139030 Group number: 44 Module code: ELEC273 Department of Electrical Engineering

% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1

% --- Executes on selection change in listbox2.function listbox2 Callback(hObject, eventdata, handles)% hObject handle to listbox2 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listbox2 contents as cell array% contents{get(hObject,'Value')} returns selected item from listbox2

% --- Executes during object creation, after setting all properties.function listbox2 CreateFcn(hObject, eventdata, handles)% hObject handle to listbox2 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end

function edit3 Callback(hObject, eventdata, handles)% hObject handle to edit3 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text% str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.function edit3 CreateFcn(hObject, eventdata, handles)% hObject handle to edit3 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end

62


Recommended