Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS005 Introduction to Programming

Similar presentations


Presentation on theme: "CS005 Introduction to Programming"— Presentation transcript:

1 CS005 Introduction to Programming
Matlab Eamonn Keogh

2 More on Functions EDU>> EamonnRand = rand EamonnRand = 0.0975
The rand function returns a random number between 0 and 1 Strictly speaking, the interval is (0,1) Every time you use it, you should expect a different number. EDU>> EamonnRand = rand EamonnRand = 0.0975 0.2785

3 EDU>> EamonnRand = rand EamonnRand = 0.2856
Where is the input parameter? If you don’t use one, matlab assumes you just want a single number We can also explicitly ask matlab for a single random number like this… EDU>> EamonnRand = rand EamonnRand = 0.2856 EDU>> EamonnRand = rand(1) 0.8003

4 EDU>> EamonnRand = rand(1)*10 EamonnRand = 1.4189
Suppose we want a random number between 0 and 10 instead? We don’t need new function for this. We can just multiple rand by 10 If you want a random number between 0 and 77, just multiple rand by 77 etc. EDU>> EamonnRand = rand(1)*10 EamonnRand = 1.4189 4.2176 9.1574

5 EDU>> EamonnRand = (rand(1)*10) + 90 EamonnRand = 90.3571
Suppose we want a random number between 90 and 100 instead? We don’t need new function for this. We can just multiple rand by 10, then add 90 If you want a random number between A and B, just use A + (B-A)*rand EDU>> EamonnRand = (rand(1)*10) + 90 EamonnRand =

6 EDU>> 0 + (6-0)*rand ans = 4.5032
Suppose we want a random integer instead For example we want an electronic dice that give use a 1,2,3,4,5 or 6 First lets get a real number between 0 and 6 A + (B-A)*rand Now we want to snap the numbers to the nearest integer (almost true) EDU>> 0 + (6-0)*rand ans = 4.5032 1 2 3 4 5 6 One die, two dice

7 5 4 EDU>> round(4.5032) ans = 5 EDU>> floor(4.5032) 4
EDU>> ceil(4.5032) Matlab has three useful built-in functions that might help. round returns the nearest integer to the input argument floor returns the nearest integer that is less than or equal to the input argument ceil returns the nearest integer that is larger than or equal to the input argument 5 4

8 5 4 EDU>> ceil(0 + (6-0)*rand) ans = 4 3 1
Putting it altogether, we have our dice toss command. 5 4

9 Wrong! EDU>> ceil(1 + (12-1)*rand) ans = 3 12 2
Many games are based on the sum you get when you toss two dice. The range is 2 (snake eyes) to 12 (boxcars) So this code gives an integer between 2 and 12 Wrong!

10 EDU>> ceil(1 + (12-1)*rand) ans = 3
This code gives equal probability to all numbers from 2 to 12. However, the probabilities should differ

11 EDU>> Dice1= ceil(0 + (6-0)*rand);
EDU>> Sum_from_two_dice_throws = Dice1 + Dice2 Sum_from_two_dice_throws = 10 Our code should really “throw” two dice, like this..

12 I ran both methods 100,000 times, and plotted the distribution of numbers.

13


Download ppt "CS005 Introduction to Programming"

Similar presentations


Ads by Google