Download 06_lecture_20100202_Loops,_Random

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mathematics of radio engineering wikipedia , lookup

Location arithmetic wikipedia , lookup

Collatz conjecture wikipedia , lookup

History of the function concept wikipedia , lookup

Elementary mathematics wikipedia , lookup

Law of large numbers wikipedia , lookup

Expected value wikipedia , lookup

Transcript
Loops
1.
2.
WHILE loops
FOR loops
1.
2.
3.
4.
5.
6.
Range operator
Running totals
Random Numbers
Floor/Ceiling
Modulus
Library functions - vocabulary
1
Review









Review while loops while (time < 3:15)
Review infinite loop while (true)
Introduce for loop
for x = 1:10
Introduce range operator x=1:10 or x=1:2:10
Introduce random value generator rand
Introduce ceiling and floor functions
Sum elements in a loop
Compute average of values
Get min/max values from a loop
2
1. WHILE Loop - Review

Generally you have a loop control variable, this
variable has 3 phases




Initialization of variable
Change of variable
Condition to exit loop
Example: the loop control variable is x
x = 0;
 1. initialization
while ( x < 10)
x = x + 1;
fprintf(‘%02d\n’, x);
end
 2. condition
 3. change loop variable
3
Loops Review

Infinite Loop  Loop control variable never
meets the condition and the code runs and
runs…….

Use CTRL C in the command window to
break it
4
Loop Review
Why is this an infinite loop in MATLAB?
x = 11;
% 1. initialization
while ( x > 10)
fprintf(‘%02d\n’, x);
x = x + 1;
end
% 2. condition
% 3. change loop variable
5
Trap a user for a value


Ask a user for a value between 1 to 10
What if they don’t give the proper value?
Two approaches:


Ask first, then loop
Make bad and loop
6
Validate input, cont.
Ask first, then loop:
numValues = input(‘Value from 1-10: ’); %ask first
while (numValues<1 || numValues>10)
numValues = input(‘Error! Enter a value 1-10: ’);
end
Make bad, then loop:
numValues = -1; %makes loop run at least once
while (numValues<1 || numValues>10)
numValues = input(‘Value from 1-10: ’);
end
7
2. FOR Loop



Generally used for a fixed number of iterations
You know you want to go from 1 to 100, by ones
for syntax does all 3 parts of the loop in one line
initialization, change, condition
for i = 1:100
disp(i);
end
The symbol : is a new
operator, it’s the range
operator. The range is
from 1 to 100, by ones.
We say “in steps of one”
If you want to loop in
steps of 2, use 1:2:100
8
Range Operator [:]

for loops use the range operator to specify a range of
values to loop over (to iterate)

Syntax:
variable = start : increment : end
: increment is optional – defaults to : 1 if omitted
9
Range Operator, cont.
Examples:
(in all examples, there is an implied loop body (code-block), and end)
% loop 10 times
for x = 1:10
% None of the values MUST be integers
for y = 1.2 : 2.3 : 100.5
% Can use negative steps
for z = 10:-2:1
Steps of -2 will never “hit” the value
of 1…
So… when does it stop?
10
Range Operator, cont.
The loop continues as long as the value is “in the
range” specified
for ctr=1:3:10
% as long as 1<=ctr<=10
for val=-5:2:5
% as long as -5<=val<=5
for thing=5:-3:0
% as long as 5>=thing>=0
11
FOR loops, cont.
Which brings up a very important issue:
It is possible to change the loop counter in a
FOR loop
This is normally not a good idea since the
value will be changed in the next loop
iteration
12
FOR loops, cont.
for cnt=1:5
fprintf(‘%d\n’, cnt);
cnt = cnt * 2;
end
Output:
1
2
3
4
5
>>
Notice that the variable changed
back at the top of the loop
13
Nested for loops
Generate a table of output that looks like a clock for every
second of the day
for hr= 0:23
% all hours for day
for min = 0:59
% all minutes per hour
for sec = 0:5:59
% all seconds per min per hour
fprintf(‘%02d:%02d:%02d\n’, hr, min, sec);
end
end
%01:05:05d
end
Test the Code!
Write a program that prints all days of the year for the decade, Year, Month, Days
14
Loops: Running total / products

Loops are useful for accumulating or summing values..computing
averages, totals etc. (“running totals”, “running products”)

Running total:
 Start with a variable for the sum initialized to 0
sum = 0;


Each time through loop add a value to the sum:
sum = sum + number;
Running product:
 Start with a variable for the product, initialized to 1
prod = 1;

Each time through loop, multiply:
prod = prod * number;
15
Loops: Running total
% initialize values
total = 0;
value = 0;
%loop when value positive or zero
while value >=0
fprintf('Negative values quit…\n')
value = input('Enter a positive integer: ');
if value >=0 %add value if positive
total = total + value ;
end % of if
end % of while
%display result
fprintf('total = %d\n', total);
16
Loops: Compute Average
1.
Initialize sum before the loop
sum = 0;
2.
Keep a running total:
sum = sum + number;
3.
After loop, divide by count
average = sum / iterations;
17
3. Random Numbers



rand - generates a pseudo random number
between 0 and 1 (exclusive)
never 0 and never 1: some value between.
Go to MATLAB



>> rand
>> help rand
Big picture: Why use random numbers?



Create tables of data so you can test code
Let computer decide who starts a game (player 1,2,3…?)
Introduce random events when testing software (1 signifies
main engine is down, 2 signifies fuel sensor error...)
18
FOR Loop: Average

Generate 10 random values (between 0 and 1)
and compute average
%initialize variables
sum = 0;
average = 0;
%loop 10 times
for x = 1:10
value = rand; %generate 1 random value ]0-1[
fprintf(‘value %02d is %.3f\n’, x, value);
sum = sum + value;
end
%calculate, display average
average = sum / 10;
fprintf (‘the average is %.3f\n’, average);
19
Output result
First run:
Second run:
value 01 is 0.906
value 02 is 0.127
value 03 is 0.913
value 04 is 0.632
value 05 is 0.098
value 06 is 0.278
value 07 is 0.547
value 08 is 0.958
value 09 is 0.965
value 10 is 0.158
The average is 0.558
value 01 is 0.971
value 02 is 0.957
value 03 is 0.485
value 04 is 0.800
value 05 is 0.142
value 06 is 0.422
value 07 is 0.916
value 08 is 0.792
value 09 is 0.959
value 10 is 0.656
The average is 0.710
20
4. floor/ceil Functions

floor and ceil
(ceiling) functions
convert fractional
numbers into
integers. Similar to
rounding but instead
they take the next
integer lower for
floor, higher for
ceil
val
ceil(val)
floor(val)
.001
1
0
.9
1
0
.25
1
0
1
1
1
5.8
6
5
-3.25
-3
-4
21
Combine rand with ceil

Lets say you are rolling a dice, rather then asking the
user: dice = input(‘select roll (1-6): ’)

Let Matlab pick a random number:
dice = ceil(rand * 6)
1.
2.
3.
4.
rand gives you .01 .. 0.99
Six times that gives you .06 .. 5.94
ceil(.06)  1
ceil(5.94)  6
Thus you get random values for dice between 1..6
22
Combine rand with floor


What if you want values from 0 to 5
value = floor(rand * 6);
1.
rand gives you .01 .. 0.99
2.
Six times that gives you .06 .. 5.94
floor(.06)  0
floor(5.94)  5
3.
4.
Thus you get random values from 0 to 5 inclusive using
the command:
value = floor(rand*6);
23
Pick a random value between
-10 and 10

What if you want values from -10 to 10 inclusive?

value = floor(rand * 21) - 10
1.
2.
3.
4.
5.
rand gives you .01 .. 0.99
21 times that gives you .21 .. 20.79
floor(.21)  0
floor(20.79)  20
Subtract 10 gives you -10 to 10 inclusive
Thus you get random values from -10 to 10 inclusive using
the command:
value = floor(rand * 21) - 10
24
For Loop-Roll Dice 10 times

Combine the for loop, with ceil, and rand
%loop 10 times
for x = 1:10
dice = ceil(rand*6); %generate a dice roll
%display
roll 1 is 1
fprintf(‘roll %d is %d\n’, x, dice); roll 2 is 6
roll 3 is 6
end
roll 4 is 5
roll
roll
roll
roll
roll
roll
5 is 5
6 is 5
7 is 3
8 is 4
9 is 2
10 is 5
25
5. Loops: Find Min / Max


Trying to find a min value or max value
First time through the loop, set the minimum and
the maximum value to the number.
if (count == 1)
min = number;
max = number;
end

Each subsequent time, determine if the number
> maximum if so, reset the maximum value to
the number
if (number > max)
max = number;
end
There are also functions min()
and max() – we will use them
26
later with vectors & arrays
Taboos
http://www.egr115.com/taboos.pdf
Don’t use these words in your programs:
• global
• error
• persistent
• exit
• break
• quit
MAJOR points
lost for using
these in your
programs!
• continue
27
6. Modulus

help mod

Determines the long division remainder value
mod(2, 2) 0
mod(3,3) 0
mod(3,2) 1
mod(4,2) 0
mod(5,2) 1
mod(4,3)
mod(5,3)
mod(6,3)
mod(7,3)
1
2
0
1
mod any number with N, the function will return from 0 to N-1
If evenly divisible, mod will return 0 i.e mod (6, 3) or mod (100, 10)
28
Combine for / rand / mod



Write a program that picks 200 random
integers between 1 .. 100
Determine how many are odd and how many
are even
Print out the # of odd values, # even values,
and compute the percentages of odd and
even values
29
An algorithm
for ???
pick rand number
if odd
Increment odd counter
else
Increment even counter
end
end
Compute odd percentage
Compute even percentage
Print out results
Note counters need to
be INITIALIZED to 0.
Before or in the loop?
30
Solution
% set up counters
odd_cnt = 0;
even_cnt = 0;
%loop to create/analyze numbers
for cnt=1:200
value = floor(rand()*100) + 1;
if mod(value, 2) == 1 %even number
odd_cnt = odd_cnt + 1;
else %odd
even_cnt = even_cnt + 1;
end
end
Notice the lack of
semicolons (;) in FOR and
IF statements
%calculate/display results
odd_pct = 100* odd_cnt / 200;
even_pct = 100 * even_cnt / 200;
fprintf(‘%.2f%% were odd,’, odd_pct);
fprintf(‘and %.2f%% were even\n’, even_pct);
31
How long to generate random
#’s
Write a program that generates random numbers from
1 – 100
 Keep running program ‘til every number gets one
occurrence. – that’s an array problem, have to do that in
a week or so…

32
LIBRARY FUNCTIONS
33
Library Functions
What is a function?
Generally, a function is a set of commands which are
grouped to perform in sequence, like a program. The
function is provided a name so that a new program can
use the function.
Functions are a foundation of “modularity” – when we’ve
solved a problem, let’s allow it to be reused. If there’s a
problem with the solution, we can fix the function without
re-writing the programs that use.
34
Library Functions, cont.
We have already used or seen several functions:
clc, clear, fprintf, input, rand, floor,
ceil
“Libraries” are groups of functions usually related in some
way.
Those functions listed above are considered “library
functions” because they are provided as a group with
MATLAB – we don’t have to write them ourselves.
35
Library Functions, cont.
A few of the many, many MATLAB functions:





sin(), cos(), tan()
sind(), cosd(), tand()
asin(), acos(), atan()
asind(), acosd(), atand()
exp(), sqrt(), log(), log10()
36
Library Functions, cont
When we use a function we say that we are “calling the
function”. The code calling the function is referred to as
the “function call”:
v = 6 * rand();
The function call
37
Function Calls
Functions frequently require information to achieve the goal
for which they were written. This information is sent to the
function inside parentheses after the name of the function
in the function call:
x = sqrt(a);
a is an “argument”
to the sqrt()
function.
The values sent (there may be more than one) are called
arguments to the function.
38
Function Calls, cont.
A function, when executed, typically sends information back
to the program that asked it to execute.
We say that the function “returns a value” - it has a return
value. If we choose to, we can “collect” the return value:
we save it in a variable.
39
Function Calls, cont.
We usually choose to collect the return value:
X = sqrt(a); X collects the return value
But not always – you don’t usually see this:
Y collects the return value
Y = fprintf(‘Hello!’)
40
Function Calls, cont.
Not all functions return values. But many do.
You, the programmer, MUST provide the arguments when
calling a function.
You, the programmer, MAY choose to collect the return
values.
41
Function Calls, cont.
Terminology summary
Function call – the command that executes a function
Arguments – inputs to a function call
Return values – outputs from a function call
42