Vous êtes sur la page 1sur 0

1M COMPUTING 2002-2003 1

RPT page 1 of 6 20/11/02


TUTORIAL EXERCISE 1
REVISION & GETTING GOING
Most of the work here should be done in pairs, except the email and cv sections.
Web Check: UG Courses
Open the a browser (Netscape Navigator or Internet Explorer)
Open the page www.me.ic.ac.uk (unless it is already open).
Follow the STUDY link and see the resources are available. These include:
timetables:
subjectscourse timetable
year photos:
general information current students
regulations on plagiarism, calculators in exams and marking schemes:
undergraduatesregulations
lecture notes:
subjectssubject lecture notes
Web Check: PDP
Open the page www.ice.ic.ac.uk
Add this page to your favourites you will be asked to use it later in the year.
Spend 5 minutes now seeing what is on this site, to help you with your Personal
Development Plan.
Web Check: MechSoc
Open the page www.cgcu.net/mechsoc
This is your student society. If it is out of date, encourage the officers to update it!
1M COMPUTING 2002-2003 1
RPT page 2 of 6 20/11/02
Email
Every student needs to do this part of the exercise individually not in pairs. It may be
best if you are sharing a computer for one of you to do it, and then log off before letting
the other person complete it.
This exercise should test that your email is working.
Start up your email.
Open the CV proforma
Save it to your own portion of the hard disk (H:) with a name that involves your initials.
For example, if your initials were "ABC" you might save it as "ABCcv.doc".
Word Processing Exercise: Your CV
Start writing your own CV, by opening your cv if it is not already open. For example,
enter your full name, date of birth and age.
Save the document.
If you are sharing a computer, log off and let the other person do the exercise down
to this point. This way we will confirm that all accounts and emails are working.
THE CV EXERCISE HERE SHOULD BE COMPLETED
BEFORE YOUR NEXT COMPUTING TUTORIAL (IN
APPROXIMATELY 2 WEEKS), BUT DO NOT DO IT NOW.
The exercise for completion during the tutorial continues overleaf
1. Complete your cv no more than 2 pages maximum.
2. email the complete cv to Dr Weightman (b.weightman@ic.ac.uk)
3. Print out the complete cv and give it to your personal tutor next time you see him/her.
NB Printing instructions are given on the back of this tutorial sheet.
Optional hints for good use of word processing
Try NEVER to have two consecutive paragraph marks. Instead, learn how to format
paragraphs with spacing Format Paragraph Indents and Spacing
Try NEVER to have two consecutive spaces. Instead, learn how to set and use tabs
Format Tabs
Try using Styles to ensure that all similar text appears in the same font and size, etc.
eg, in the cv document you are supplied with, select the heading "Personal Details"
and change the colour of this to red. Now click in the style box (it appears as
Heading 2) and then choose Update the Style to Reflect Recent Changes
1M COMPUTING 2002-2003 1
RPT page 3 of 6 20/11/02
SPREADSHEET REVISION & MATLAB INTRODUCTION:
CALCULATION AND PLOTTING FUNCTIONS OF ONE VARIABLE
Mass and Momentum Flow Rate in a Pipe
(This problem comes from the first year fluids course). The speed of the air through a
pipe at a particular point is dependent on the distance of that point from the centre.
Given a series of values of the speed at various radii, calculate the total mass flow rate
and momentum flow rate in the pipe.
r
r
r out
in
U
Method
Consider an annulus of the cross section of the pipe (shown shaded in the picture). The
inner and outer radii of this annulus are r
in
and r
out
respectively, so the width of the
annulus is given by
r = r
out
r
in
and the radius of a point halfway across the annulus is given by
r =
r
out
+ r
in
2




If the speed at this radius is ( ) r U , and the density of the air is , then the mass flow
rate is
( ) r rU r m 2 =
and the momentum flow rate is
( ) ( )
2
2 r U r r M =

If the whole of the cross section of the pipe is divided into several annuli then the total
mass flow rate can be calculated as

=
i
i
m m
and the total momentum flow rate can be calculated as

=
i
i
M M

1M COMPUTING 2002-2003 1
RPT page 4 of 6 20/11/02
Spreadsheet
Heading for whole sheet
The radius of the pipe is 0.1m. You will divide it into 10 annuli, each of width 0.01m.
In cell A1 of the spreadsheet type "MASS AND MOMENTUM FLOW RATE IN A
PIPE"
Headings for columns of data
In cell A2 type "i". Then press <TAB>
In cell B2 type "rin"
In cell C2 type "rout"
In cell D2 type "r"
In cell E2 type "dr"
In the next few cells in row 2 type headings for the other columns, these will include
speed, mass flow and momentum flow.
Radius Values
In the first column enter the values for i for the different annuli
In cell A3 type 1. Then press <RETURN>
In cell A4 type 2
etc until
In cell A12 type 10
Alternatively, this can be done by entering 1 in cell A3 and then holding the <CTRL> key
down, drag the corner of the cell A3 down to cell A12.
In the second column enter the inner radius of each annulus
In the third column enter the outer radius of each annulus
Simple Functions
In cell D3 type "=(B3+C3)/2" and <ENTER>. In this cell the average value of the values
in B3 and C3 will appear.
In cell E3 type "=" then click on C3 then type "-" then click on "B3" and then <ENTER>.
In this cell the difference between C3 and B3 will appear.
Click the mouse on cell D3 and while the button is
still pressed, drag it to cell E12 so that all these
cells are highlighted.
From the Edit menu choose Fill Down. The
correct formula should now have been entered in
all the cells in the column.
Flow Speeds
In the next column enter the speeds as given:
i Ui
1 1.00
2 0.99
3 0.96
4 0.91
5 0.84
6 0.75
7 0.64
8 0.51
9 0.36
10 0.19
1M COMPUTING 2002-2003 1
RPT page 5 of 6 20/11/02
Density
In cell A14 enter "Density" and in cell B14 enter "1.225".
Mass and Momentum Flows
In column G enter a formula for the mass flow, it will be something like
"=2*PI( )*D3*E3*F3*B14". Fill the rest of the column with suitable values. Notice that
you get errors. This is because for the first cell, the density is B14, but for the
second one it is B15. This needs changing.
In cell G3 Change "B14" to "$B$14" and now fill the column. This means that the value
of B14 is always to be used, rather than the value which is six columns to the left and
11 columns down.
In column H enter the momentum flow rates.
In row 14, add up the mass and momentum flows to give totals. To do this you will
probably want to use the icon above the sheet. At this stage your spreadsheet
should look something like that shown in these notes.
Look in the cell to see how the function "SUM" is used. There are many other functions
available under the Insert menu and Function command or f
x
button.
Importance of Outer Portion of Pipe
See if you can modify the spreadsheet to tell you what proportion of the momentum flow
is within the five central annuli. (Answer about 53%).
The Graph
Create a graph (Chart) in Microsoft Excel showing how the momentum flow rate varies
across the width of the pipe. Show the resulting graph to a tutor.
Check Point Student's Name(s) Tutors' Initials Date
Ask a tutor to check and sign your
work before you proceed or leave
MATLAB
Repeat the problem, this time solving it by using Matlab as outlined in the Lecture.
Create a Plot showing how the momentum flow rate varies across the width of the pipe.
Check that the answers are the same, and output the graph to a file using the File
Export command. Ensure that your name(s) are on the plot.
Create a short document in Microsoft Word which contains the plot and a short
description (max side including plot). Save the Word document.
1M COMPUTING 2002-2003 1
RPT page 6 of 6 20/11/02
More Plots
Using the following definitions
( ) sinh
2
x x
e e
x

= (1)
( ) cosh
2
x x
e e
x

+
= (2)
( )
( )
( )
sinh
tanh
cosh
x x
x x
x e e
x
x e e

+
= =

(3)
( ) ( ) ( )
2 2
sinh cosh f x x x = (4)
plot a graph showing ( ) ( ) ( ) ( ) sinh , cosh , tanh and x x x f x against x over the range
3 3 x . Ensure that all the curves are different colours.
Add a suitable title.
You may find some of the following helpful:
hold on
Export the plot, and include it in your previous Microsoft Word document with a brief
description.
Polar Plot
Using the definition
( ) ( ) 3 2cos r = + (5)
plot a polar graph of the function ( ) r for the range 0 2
You may find some of the following helpful:
theta = 0: 0.1: 2*pi
polar (theta, r)
Again export the plot, and include it in your previous document with a comment.
Show this to one of the tutors.
Check Point Student's Name(s) Tutors' Initials Date
Ask a tutor to check and sign your
work before you proceed or leave
If you wish, Print your file, but be sure to use Properties on the Print page, and select
2 pages per sheet. Your total document should then fit on 1 sheet.
1M COMPUTING 2002-2003 2
RPT page 1 of 4 20/11/02
TUTORIAL EXERCISE 2
MATRICES AND 3D PLOTS
Matrix Calculations
Work out (by hand) the following matrix calculations. Write the answers on this sheet.
Then repeat the calculations in MATLAB and check that you've got them right.
1 2 0 1
3 4 2 3


+ =





3 1 6 0 2 3
5 4 2 4 0 6
1 3 8 7 8 0




+ =






1 2 0 1
3 4 2 3


=





3 1 6 0 2 3
5 4 2 4 0 6
1 3 8 7 8 0




=






Using MATLAB calculate the following:
2
1 2
3 4


=





1
1 2
3 4



=





1
1 2 1 2
3 4 3 4



=





1M COMPUTING 2002-2003 2
RPT page 2 of 4 20/11/02
Solving Linear Equations
Solve the following equations using MATLAB:
3 1 6 1
5 4 2 12
1 3 8 3
x
y
z


=


You will probably do this by calculating as follows. Fill in the answers here. Check your
results by hand.
1
3 1 6 1
5 4 2 12
1 3 8 3
x
y
z





= =





Loading and Saving
Copy the file currentmatrix.mat from the ugshare portion of the hard disk onto your
own area.
Change the working directory to wherever you have saved the file.
Load the file currentmatrix.mat into MATLAB using load currentmatrix
Check to see that the variable currentmatrix contains the following matrix
1 1 0 0 0 1 0 0
0 1 1 0 0 0 1 0
0 0 1 1 0 0 1 0
0 0 0 1 1 1 0 0
2 0 0 0 1 10 0 100
0 3 0 4 0 10 8 0
0 0 13 0 0 0 8 0




Check the size of the matrix using the size function.
Set A to be a matrix containing the first seven columns of this matrix.
Set b to be a matrix containing the last column only of this matrix.
Repeat the calculation that was done in the lecture to solve the current network and
check that you now get the same answers. Put the answer in a column vector called i.
Save the matrices A, b, and i to another file.
1M COMPUTING 2002-2003 2
RPT page 3 of 4 20/11/02
Another Current Problem
The Figure shows another electrical circuit. You are
to solve this for the currents as shown.
Write down the six unknowns that exist here:
1 2 3 5 6 4
, , , , , I I I I I I
Check that you agree with these equations for
the currents at each junction point.
+ + =
+ + =
+ =
+ =
1 2 3
3 6 4
2 5 4
5 6 1
0
0
0
0
I I I
I I I
I I I
I I I
Similarly, check that you agree with the
following equations for the voltages around the circuits. Note that these equations
between them include every resistor and the 15V value.
=
+ =
+ =
2 3 4
5 6 4
3 6
2 3 0
3 4 5 0
2 5 15
I I I
I I I
I I
There are more equations than unknowns here. Therefore, one of the current
equations is redundant (ie can be made from adding together multiples of the others
eg the last one can be made by adding the others together). Cross is out. Check that
you now only have the same number of equations as unkonwns. Rewrite all the remaining
equations in matrix below.
Solve the equations in MATLAB and give the resulting values of current:
1
2
3
4
5
6
1 1 1 0 0 0 0
0 0 1 1 0 1 0
0 1 0 1 1 0 0
0 1 2 3 0 0 0
0 0 0 3 4 5 0
0 0 2 0 0 5 15
I
I
I
I
I
I








=










Hence:
1
2
3
4
5
6
5.16
3.20
1.97
0.24
2.95
2.21
I
I
I
I
I
I









=











Show the results to a tutor
Check Point Student's Name(s) Tutors' Initials Date
Ask a tutor to check and sign your
work before you proceed or leave
I
1
I
1
I
3
I
2
I
4
I
6
I
5
15V
1
2
3
5
4
Figure An electrical circuit
1M COMPUTING 2002-2003 2
RPT page 4 of 4 20/11/02
Graphs
Plot a graph of the function ( ) ( ) cos cos cos sin z x x y = + + over the range
2 2 x and 2 2 y where is a constant, and = 45. This is graph of two
waves crossing at an angle of . Remember that sin and cos calculate in radians.
Supplementary exercises from Magrab
E.B. Magrab, An Engineer's Guide to MATLAB, Prentice Hall, 2000.
You should now be in a position to work through any or all of the examples and exercises
from chapters 1 & 2 of this book. If you lack confidence, then you are recommended to
try as many exercises as you need.
Worked example ("square wave")
Magrab Exercise 2.14 (a): Plot the series below over the indicated range of t. Use 100
terms to sum each series
( ) ( )

=
=

1 1
2 2
1,3,5,
4 1
sin 2
n
f t n t t
n
Create the vectors n and t to contain the n values for the series and all the values of t to
be used, ie:
( )
( )
=
=
1 3 5 ... 201
0.5 0.49 0.48 ... 0.5
n
t
By multiplying the matrix n' by t appropriately, create a matrix whose first column is the
values of
( )
sin 2n t for the first value of t, the second column is for the second value
of t etc.
( )
= sin 2 ' M n t
Create a matrix p from n as follows using "dot divide", ie ./
( ) =
1 1 1
3 5 201
1 ... p
Now multiply p and M, and you should be left with a row of values of f(t). Note that
Matlab automatically does the summing for you. Why is this?
= f p M
Further example ("saw tooth")
Magrab Exercise 2.14 (b). Calculate similarly for
( ) ( )

=
= +

1
1 1 1
sin 2 1 1
2
n
f t n t t
n
1M COMPUTING 2002-2003 3
RPT page 1 of 4 20/11/02
TUTORIAL EXERCISE 3
SCRIPTS
Theory of Line of Best Fit
For a set of data points ( ) ( ) ( ) ( ) { }
1 1 2 2 3 3
, , , , , , , ,
n n
x y x y x y x y , the straight line which
best fits the points is y mx c = + , for values of m and c that have to be calculated. The
formulae for these values can be shown to be as follows using matrix notation:
1 1
2
1 1 1
n n
i i
i i
n n n
i i i i
i i i
c n x y
m x x x y
= =
= = =





=







(1)
or,
1
1 1
2
1 1 1
n n
i i
i i
n n n
i i i i
i i i
c n x y
m x x x y

= =
= = =





=







(2)
This will be used a bit later.
Graph
The file 'waterdata.mat' contains the values of temperature and absolute pressure for
saturated water and steam. It is a MATLAB .mat file, containing (1) T , temperature
values and (2) corresponding p , pressure values.
Copy the file to your area of the hard disk.
Change your working directory to be the one where the file now is
Load the file into MATLAB using the instruction load "waterdata "
Now have a look at the variable data. You should see two variables, T and p,
temperature and pressure respectively.
Plot the points on a graph with red crosses with T along the x-axis and p along the y-
axis.
1M COMPUTING 2002-2003 3
RPT page 2 of 4 20/11/02
m-file
Create a new .m file. If your initials are rpt , then Save the file with the name
waterrpt.m using the File Save As command.
Add comments to the top of the file indicating who wrote it, when, and what it's
purpose is. (You are going to write the instructions in the file to do a linear
approximation to some data). Remember that comments begin with %
Add to the .m file commands to draw the graph that you created above.
Run the .m file and check that it works properly.
FROM NOW ON, SAVE AND RUN YOUR FILE FREQUENTLY TO CHECK THAT IT
IS WORKING AND PRODUCING SENSIBLE RESULTS.
Line of Best Fit
As described in the lecture, and given in
the formulae above, calculate the line of
best fit for the data, and draw it on the
graph (all in MATLAB). Give here the
values, and sketch the line of best fit once
MATLAB has drawn it for you.
m = ...........................................................
c = ............................................................
1 1
2
1 1 1
n n
i i
i i
n n n
i i i i
i i i
c n x y
m x x x y
= =
= = =





=







FILL IN THE VALUES:
1 1
2
1 1 1
n n
i i
i i
n n n
i i i i
i i i
n x y
x x x y
c
m
= =
= = =




=









0 20 40 60 80 100 120 140 160 180 200
-4
-2
0
2
4
6
8
10
12
14
Sketch line of best fit on graph
1M COMPUTING 2002-2003 3
RPT page 3 of 4 20/11/02
Quadratic of Best Fit
In fact, because the data in this example definitely does not form an approximately linear
relationship, the results are very poor. Therefore, it is better to try to fit a quadratic to
this data.
For a set of data points ( ) ( ) ( ) ( ) { }
1 1 2 2 3 3
, , , , , , , ,
n n
x y x y x y x y , the quadratic (or parabola)
which best fits the points is
2
2 1 0
y a x a x a = + + , for values of
0 1 2
, , a a a that have to be
calculated. The formulae for these values can be shown to be as follows using matrix
notation:
2
0
1 1 1
2 3
1
1 1 1 1
2 3 4 2
2
1 1 1 1
n n n
i i i
i i i
n n n n
i i i i i
i i i i
n n n n
i i i i i
i i i i
n x x a y
x x x a x y
x x x a x y
= = =
= = = =
= = = =








=












or,
1
2
0
1 1 1
2 3
1
1 1 1 1
2 3 4 2
2
1 1 1 1
n n n
i i i
i i i
n n n n
i i i i i
i i i i
n n n n
i i i i i
i i i i
a n x x y
a x x x x y
a x x x x y

= = =
= = = =
= = = =








=












Using MATLAB, calculate the values of
0 1 2
, , a a a . Do all the calculations by typing the
commands into your .m file, saving it and running it. Fill in the following:
2
1 1 1
2 3
1 1 1 1
2 3 4 2
1 1 1
1
0
1
1
2
n n n
i i i
i i i
n n n n
i i i i i
i i i i
n n n n
i i i i i
i i i i
n x x y
x x x x y
x x x x y
a
a
a
= = =
= = = =
= =

= =






=









Hence
2
y x x = + +
1M COMPUTING 2002-2003 3
RPT page 4 of 4 20/11/02
Plotting best fit quadratic & cubic
Now that you have calculated the required values, plot the quadratic of best fit on the
same graph as before.
Write here the lines that you use in your .m file to do this.
You should find now that the parabola is a much better fit than the straight line. This
process can be repeated for higher orders of fit. The matrices follow the same pattern.
However, the function polyfit is already designed to do this.
Read the help on the polyfit function, then
use the function to calculate and draw the best cubic for the data.
Add the appropriate lines to your .m file.
Show the resulting graph and the .m file that produced it to a tutor with
original data with red crosses
linear fit
parabola (ie quadratic) fit
cubic fit
Check Point Student's Name(s) Tutors' Initials Date
Ask a tutor to check and sign your
work before you proceed or leave
Supplementaries: Magic & Rand
What does the function magic do? Read the help and then check to see what the function
sum does on a matrix. Try
M = magic(5)
sum (M)
sum (M')
What does the function rand do? Use it to simulate rolling a dice.
Magrab
Continue with exercises in Magrab chapters 1 & 2 and now save results in .m files. Eg 2.19
1M COMPUTING 2002-2003 4
RPT page 1 of 4 20/11/02
TUTORIAL EXERCISE 4
VARIABLES & LOOPS
The Four-Bar Link Problem
a
b
c
d


Figure Diagram of the lengths and angles of a four bar link
The equation relating the output angle to the input angle of a four bar link is
( ) ( )
( )
( )
2 2 2 2
cos cos cos 0
2
d a b c
d d
c a ac

+ +
+ = (1)
This exercise below is to write a MATLAB script to solve the above equation for various
values of . Recall that the Newton-Raphson method calculates the solution to
( ) 0 f =
where in this case
( ) ( ) ( )
( )
( )
2 2 2 2
cos cos cos
2
d a b c
d d
f
c a ac

+ +
= + (2)
It may help to know that
( ) ( ) ( ) = ' sin sin
d
f
a
(3)
The Script
Change the MATLAB path, and open a new script file.
Put comments at the top of the script which include the author's name, purpose and
date.
put values 0.2 m a = , 0.5 m b = , 0.4 m c = , 0.6 m d = near the top the script
(clearly the units will be left out!)
1M COMPUTING 2002-2003 4
RPT page 2 of 4 20/11/02
Also use the input function to ask the user for the relevant input angle, (in degrees).
Add a line to turn the value into radians.
Put a value for precision = 0.001 in the script.
Check that the script file runs and does not give errors at this stage.
The Loop
Insert the correct lines to start and end an appropriate loop. This will be either of
this form for a for loop. (NB the <terms> in diamond brackets should be replaced with
sensible expressions):
for <variable> = <start>:<end>
end
or of this form for a while loop:
while <condition>
end
The Newton-Raphson Method
Recall the Newton-Raphson iteration technique for finding the value of x for which
( ) 0 f x = is as follows:-
(i) Estimate an initial value of x and call it x
0
(ii) Calculate
( )
( )
0
1 0
0
'
f x
x x
f x
= (4)
(iii) Repeat step (ii) with
( )
( )
1
'
n
n n
n
f x
x x
f x
+
= (5)
until the sequence x
n
converges.
Add appropriate lines to the script to do these calculations, and ensure that the loop
stops when the correct condition is reached. The initial value is not particularly
critical, but a good first estimate is equal to 45
4

=

.
1M COMPUTING 2002-2003 4
RPT page 3 of 4 20/11/02
Results
What are the values of output angle for the following values of input angle . One value
is given to help you check that you are getting the right answers. (Ensure that you have
turned the results back into degrees from radians).
(i) = 0 ................................................ (ii) = 10 ...........................................................
(iii) = 20 ............................................ (iv) = 30 ................................... 41.2
Calculating results for many values of
Up to this point a script file has been created which calculates one value of for one
value of , but actually it would be useful to be able to see the behaviour of plotted
against for a full range of values, 0 360

.
Near the top of your script, create a vector which contains 37 values starting with 0
and then evenly spaced finishing with 360.
( ) 0 10 20 360 =
Create another vector of the same size which will store all the values of , but at this
stage it will just contain all zeros.
Now put the whole of the Newton-Raphson calculations inside a for loop, for example:
for i = 1:length(phi)
end
At the beginning of the loop select the ith value of the vector to use in the
calculations and just before the end of the loop ensure that the result is put in the
correct position in the vector.
Plot (y-axis) against (x-axis) on a graph. You should get a graph something like that
shown on the next page. Show this graph and the script file which produced it to a
tutor.
Check Point Student's Name Tutors' Initials Date
Ask a tutor to check and sign
your work before you proceed
or leave
1M COMPUTING 2002-2003 4
RPT page 4 of 4 20/11/02
0 50 100 150 200 250 300 350
0
10
20
30
40
50
60
70
80
90
phi
t
h
e
t
a
input and output angles for a four bar link
Figure plot of input and output values for the four bar link shown in the original figure.
Fair Game
(For further details on this look in any elementary book on statistics. A chi-squared test
with 5 degrees of freedom is the technical term for what is happening here).
In the previous tutorial you used the rand function to simulate a dice being thrown. Using
the same method, and a suitable loop, generate 1000 dice throws and count how many 1's,
2's, etc there are. Plot these numbers on a graph. Does the dice look fair to you?
A method of calculating fairness is using the following formula where o
i
is the observed
number of times an event occurs (eg the observed number of 3's) and e
i
is the expected
number of times that event should occur (eg the expected number of 3's one sixth of
the total throws):
( )
2
2
1%,5
all possible values
i i
i
o e
e


=

(6)
In this example if the following holds, then there is no evidence to show at the 99%
confidence level that the dice is unfair:
2
1%,5
15.09 < (7)
Do you now conclude that the dice is fair? (For a typical example, I got
2
1%,5
3.50 = ).
Magrab Exercises
Further examples of questions can be found in Magrab chapter 4. In particular, you should
be in a position to do exercises 4.1 to 4.5.
1M COMPUTING 2002-2003 5
RPT page 1 of 4 20/11/02
TUTORIAL EXERCISE 5
CONDITIONS
Interval halving
The calculation of the modes of natural frequency of a cantilever built in at one end and
simply supported at the other involves the calculation of a root of the equation
( ) ( ) = tan tanh
The first mode of vibration occurs at the first positive root of the equation, when
3 < < 4. You will use the method of interval halving to find the root.
(Interval halving means: first test to see if the root is between 3 and 3.5 or between 3.5
and 4. Supposing it is the latter, for the next stage, test if the root is between 3.5 and
3.75 or between 3.75 and 4. Repeat until the root is known to sufficient accuracy).
Create a new MATLAB script file, and add the normal comments to say who wrote it,
when, why etc.
Make new variables
left = 3.0;
right = 4.0;
precision = 0.001;
Add an appropriate while loop with the condition that you need to be sure you have
calculated the answer to 3 decimal places:
while (right - left > precision)
%calculations go here
end
Inside this loop, calculate mid as being the average of left and right. Then follow that
with a calculation lines similar to the following which adjusts either the left end of the
interval or the right end of the interval.
f = tan(mid) - tanh(mid)
if (f < 0) % ie root in right half
%do something here
else
%do something else here
end
After the end of the loop display the answer and fill it in here:
Final answer (to 3 decimal places): = .............................................
1M COMPUTING 2002-2003 5
RPT page 2 of 4 20/11/02
Estimate of
One way of estimating is as follows:
Generate a large set of random x and y values with
0 x 1 and 0 y 1. Any of the (x, y) points which lie
less than distance 1 from the origin lie within a
quadrant of the circle radius 1 centred on the origin.
A fraction /4 should lie within the circle. Test each
point, and see what proportion lie within the circle.
See the Figure.
Start work in a new script file. Add appropriate
comments at the top of the file.
Set a random series of numbers using the following (see help on rand)
rand('state', sum(100*clock));
Add a constant n = 100. Follow this by a for loop which counts from 1 to n.
Set a variable (eg count) to zero before the loop.
Inside the loop generate a random point with two coordinates each between 0 and 1.
Determine whether this point is within the circle, and if so add one to the counter.
After the loop, display 4 times the fraction of points that lie within the circle.
Repeat the program for different values of n as follows, and write your answers here.
For n = 100, estimate of = .......................... For n = 1000, estimate of = ........................
For n = 10000, estimate of = .................... For n = 100000, estimate of = ..................
Is this a good method for estimating ? Why/why not? ....................................................................
Risk
The game Risk involves two players throwing dice:
Player A throws 3 dice
Player B throws 2 dice
If the highest number that Player A rolls is higher than the highest number that
player B rolls, then Player A wins.
Otherwise (including the case where both players have the same highest number)
Player B wins.
1
1
Figure: Random points will lie in
shaded area. A proportion /4 will
lie in the circle.
1M COMPUTING 2002-2003 5
RPT page 3 of 4 20/11/02
One throw each
Write a MATLAB .m file which simulates A throwing 3 dice and B throwing 2 dice, and
calculates which player is the winner. To do this you may want to use the following:
It is possible to create a whole array of random numbers using rand. The following
gives a row vector of length 3 of random numbers between 0 and 1:
rand(1, 3);
Use max to calculate As highest score and Bs highest score for comparing them
Use an appropriate if statement and an appropriate disp function to tell you who wins,
for example:
disp('a wins');
Repeated throws
Now add a for loop to your .m file to simulate repeating the throw n times, counting up
as you go how many times a wins. Use n=100.
Display to the screen how many times Player A wins. It may be helpful to use disp with
the sprintf function in the following manner (see help for details) where I have used a
variable called awin to count the total number of times Player A wins:
disp('a wins b wins')
disp(sprintf('%6d%9d', awin, n-awin))
disp(sprintf('%2.2f%% %2.2f%%', awin/n*100, (1-awin/n)*100))
Note here %6d means display as an integer using six characters
Note also %2.2f means display as a floating point number with two characters before the
decimal point and 2 decimal places
Note %% means display a % sign
Change n to 1000 and then 10000 once you are sure your program is working.
Run the .m file three times, and write the percentage of times a and b win here. On
each occasion you will almost certainly get slightly different answers:
Player A wins ..................................................... % Player B wins ...................................................... %
Player A wins ..................................................... % Player B wins ...................................................... %
Player A wins ..................................................... % Player B wins ...................................................... %
Check Point Student's Name Tutors' Initials Date
Ask a tutor to check and sign
your work before you proceed
or leave
1M COMPUTING 2002-2003 5
RPT page 4 of 4 20/11/02
Risk: Actual Probabilities
Save your .m file, and the Save it again under a new name, using SaveAs
Modify your script so that this time you calculate the actual probablilities. You will
probably use five nested loops to do this:
for i1 = 1:6
for i2 = 1:6
for i3 = 1:6
for j1 = 1:6
for j2 = 1:6
a = [i1 i2 i3];
%any other lines you want to do each time go here
end
end
end
end
end
What are the actual probabilities that A wins and that B wins?
Probability Player A wins ............................... % Probability Player B wins ............................... %
Graph of successive estimates during interval halving
It would be interesting to view what the successive estimates of the root, , which
occurred during the calculations, so a technique for doing this is introduced here:
Before the while loop, create an empty vector, calcs:
calcs = [];
Each time the loop is executed, add the current estimate to the end of calcs:
calcs = [calcs mid];
After the end of the loop, plot the vector calcs to show all the iterations:
plot(calcs);
Also plot a red line which shows the value to which the root converged
plot([1 length(calcs)], [mid mid], 'r')
Further exercises from Magrab
You are now in a position to do all the exercises on program flow control at the end of
chapter 4.