Ryerson Crest Ryerson Header

MTH 207 Lab Lesson 6

Program Control


Up to Main Lab Page Previous Lesson - Working with Functions

Topics for this Lab: With Packages $ Iteration Boolean Statements Print
For and While If...Then... Data Types - Arrays


With Packages

Maple has a full set of commands to direct program flow. This means that it is possible to write programs using Maple. In addition we can write new functions and procedures to work with Maple. There are a number of prewritten packages avalaible with Maple, you can load these packages using the with keyword. The syntax is
with(packagename);
Once a package has been loaded it will stay resident, the routines the package contains will be available for the rest of the session, or until a restart is issued. One such package is the student package (try help on student). To initiate this package you type
> with(student);

> ?student
gives help on this package and the routines it contains.
To unload the package
> restart;

The $ Iteration Operator

It is often useful to execute an operation on consectutive numbers. We can do this using the $ operator. The syntax is
expression $ x = a..b
This will evaluate expression starting at a, then a+1, then a+2 and so on until b is reached. Note that if a < b $ produces no output.
> x^2 $ x = 0..5;

By using composition we can use the iteration operator to evaluate a function at values closer and closer to a particular value. Thus $ gives us a quick and easy way to investigate the behaviour of a function near a value.
> f := x -> x^2;
> g := x -> (1 + 10^(-x));
> evalf((f@g)(x)) $ x = 1..10;
This shows the values of f at
> evalf(g(x)) $ x = 1..10;

1.1, 1.01, 1.001, 1.0001, 1.00001, 1.000001, 1.0000001, 1.00000001, 1.000000001, 1.0000000001

Note: It is recommended (and often necessary) that both expression and x be enclosed in single quotes to prevent premature evaluation. If x had been assigned a value, the x in the expression would be evaluated to its value, and so could not be used as a counting variable. The most common use is
'expression' $ 'x' = a..b;

    1. Use the $ iteration operator to investigate the value of (sin(x))/x near 0.
    2. Reset Digits to 50 and try part 1 again.
    1. Use the $ iteration operator to investigate the value of (tan(x) - x)/x^3 near 0.
    2. Based on the results of part 1, what do you think lim{x -> 0} (tan(x) - x)/x^3 is?
    3. Do 50 iterations, what do you think now?

Boolean Statements

Boolean logic in Maple is three valued, the three values are true, false and FAIL, these are reserved words in Maple.

Boolean expressions can be formed using the logical operators and, or, and not, and the relational operators <, <=, >, >=, =, and <>. Each of these operators returns either true, false or FAIL.

Symbol SyntaxExplantion
> x > a Returns true if x is greater than a
< x < a Returns true if x is less than a
>= x >= a Returns true if x is greater than or equal to a
<= x <= a Returns true if x is less than or equal to a
<> x <> a Returns true if x is not equal to a
and expr1 and expr2 Returns true if both expr1 and expr2 are true.
or expr1 or expr2 Returns true if either expr1 or expr2 are true.
not not expr Returns the logical negation of the expression expr.

Note: Maple uses the same syntax to specify ranges (see lesson 3 Ranges) as it does for boolean expressions.

The truth values for FAIL on and, or and not are given in the following table.

andornot
truefalseFAIL truefalseFAIL
truetruefalseFAIL truetruetrue false
falsefalsefalsefalse truefalseFAIL true
FAILFAILfalseFAIL trueFAILFAIL FAIL

'=' is usualy used in Maple for the definition of equations. Thus in Maple
> x = x^2;
is an assertion for which x can be solved (x = 0 or 1). Try
> solve(x = x^2);
To force Maple to evaluate = as a boolean operator we may use evalb (evaluate as boolean, c.f. evalf). Try
> x := 'x';
> evalb(x = x^2);
> x := 1;
> evalb(x = x^2);
The first evaluation is false, since in general x does not equal x2. However once we set x to 1, x does equal x2, and so the evaluation returns true.

  1. Use boolean expressions to evaluate the following.
    Let f(x) = x4 - 2x3 + 6x - 3 and define b to be 3a + 4.
    1. If a = 3 is f(x) in the interval [a, b] for any of x = 0, 1, and 2?
    2. If a = 1 is f(x) in the interval (a, b) for any of x = 0, 1, and 2?

The Print Statement

Maple has a command print, which will print the current value of its arguments to the screen.
> i := 2;
> j := y;
> f := x -> x^2;
> print(i, j, k, f);

Backwards quotes `...` are used to indicate a string in Maple.
> t :=`This is a string`;
> print(t);

Note: Maple also supports the C printf syntax.
> printf(`\t\t%g\t\t%g\t\t%g\n`, i, i^2, i^3);
If you don't know about printf yet don't worry about this.

The For and While Operators

Standard for and while loops also exist in Maple. The for and while loops in Maple are optional parts of the same structure. This means that execution can either be by steps (as in for ... next) or continue execution until a specific boolean expression evaluates to false (while ... do), or a combination of the two. The syntax is

[for < name >] [from < start expr >] [by < step expr >] [to < end expr >] [while < boolean expr >]

Note: [ ] indicates an optional phrase.
name is the name of the iterating variable.
start expression is a starting value for name (default is 1)
step expression is the step value by which name is incremented on each iteration (default is 1).
end expression is the value of name at which iteration stops.
The while statement allows for the execution to be stopped if some boolean condition, boolean expr, becomes false.
statement sequence is any number of valid Maple statements.

Examples

For can be used to evaluate functions and expressions at succesive values.

> for i from 0 by .1 to 1
> do
> print(i^2, i^3);
> od;

> f := x -> x^2 - 3*x +2;
> for i from 0 to 10
> do
> f(i);
> od;

The while expression can be used to avoid errors which might otherwise occur. The following sequence produces a divide by 0 error:
> f:= x -> sin(x)/x;
> for i from 1 by -.1 to .1 do
> f(i);
> od;
This can be fixed by using the while to stop execution if the denominator becomes 0.
> for i by -.1 to 0 while i <> 0 do
> f(i);
> od;
Note that if no from is specified, 1 is used as the default.
This is not really an ideal fix, since the execution stops at 0, what we really want is to skip 0. See If..Then below for a better way to do this.

While can also be used to stop execution when some other condition is reached. In the following example we calculate the sum of even integers until this sum is greater than 100.
> sm := 0;
> for i from 2 by 2 while sm < 100 do
> sm := sm + i;
> print(`i = `, i, `sm = `, sm);
> od;
This example highlights the problems which can occur due to Maples non linear execution in an interactive session. If you execute the above code, line by line, then go back and just execute the for loop again nothing happens the second time, why?

A common technique in iterative numerical methods is to keep evaluating until the difference between succesive approximations becomes smaller than a given value.
> Digits := 50; # Need high accuracy
> f := x -> (1-cos(x))/x; # The function to test
> err := 10^(-20); # The required error bound
> val := 100;
> oldval := 200; # Set these so that |val - oldval| > err for start
> for i while abs(val - oldval) > err
> do # Keep looping until the difference of succesive terms is less than the error bound.
> oldval := val:
> val := evalf(f(10^(-i))):
> od;

    1. Use a for loop to discover how many consecutive integers must be multiplied together until the product is greater than 10000.
    2. Let f(x) = (tan(x) - x)/x3. Use the technique above to approximate the value of f(x) near 0 with an error of succesive aproximations of 10-20.
    3. Evaluate f(10-25).
    4. Why does the method fail?

Break and Next

Flow of an iterative loop may also be halted if at any point the keyword break is encountered.

The next keyword is used to indicate that the next iteration should be started immediately, and the rest of the loop ignored.

These statements usually are used in conjuction with an if ... then statement (see below).

If ... Then ... Statements

if conditional expression then

[ elif conditional expression 2 then [ else fi;

Note: [ ] indicates an optional phrase
The conditional expressions are boolean expressions which must evaluate to either true or false.
The statement sequences are any collection of valid Maple statements.
If conditional expression is true then the statement sequence is executed.
For the optional elif (else if) statement sequence 2 is executed if conditional expression is false and conditional expression 2 is true. There may be as many elif statements as required.
For the optional else statement sequence 3 is executed if statement sequence is false and no elif branches have been taken.
Note the closing fi keyword.

Examples

> a := 3;
> b := 5;
> if (a > b) then a else b fi;

If...then can be used within loops to control special situations. Thus
> f:= x -> sin(x)/x;
> for i by -.1 to -1 do
> f(i);
> od;
Produces and error and exits when i = 0. To stop this we can use if...then together with a next statement.
> f:= x -> sin(x)/x;
> for i by -.1 to .1 do
> if i = 0 then next; fi;
> f(i);
> od;

Data Types

Maple has a wide range of data types, we have already met floating point, boolean and text strings. In fact these are all subclasses of a general type, called algebraic. Algebraic types include
integerfractionfloatstringfunctionexpresion

Maple also supports a set data type for manipulating mathematical sets.

Arrays

One important data type which we have not considered so far is arrays. Arrays are ordered sets of numbers. A one dimensional array may be thought of as a vector, a 2 dimensional array a matrix, however Maple allows any number of levels of array.

Arrays are indicated in Maple by square brackets []. Thus
> v := [1,2,3,4];
defines a 1 dimensional array (vector) whose entries are 1, 2, 3 and 4. To define a two dimensional array:
> v := [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
This gives the array

123
456
789
An array can also be initialised by using the array keyword. The syntax is
array([range 1, [range 2, ...]]...]) where the ranges are the range of each dimension. Thus
> v := array(1..4);
Defines a 1 by 4 array (vector).
> v := array(1..3,1..4);
Defines a 3 by 4 array (a matrix with 3 rows, 4 columns).

Elements of arrays can be accessed by using square brackets and an index, starting from 1. Note that arrays in Maple are indexed starting from 1. Thus
> v := [5,6,-17,4.543];
> v[1];
> v[2];
> v[3];
> v[4];

> v := [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
> v[1,1];
> v[1,2];
> v[2,1];
etc.

Arrays can be used in conjunction with for loops to store information from that iteration.

    1. See if you can implement matrix addition in Maple (this is easier than you might think).
    2. See if you can write a routine to matrix multiplication on 3 by 3 matrices.
    3. Try to implement Gaussian elimination in Maple. (this is a big exercise)
Maple has a package linalg which suppoets many of the algorithms you learnt for linear algebra (and many you probably didn't). Try
> ?linalg
to find ourt about these routines.
> with(linalg);
loads the package into Maple for use.


Look up gausselim and gausjord in the Maple help.
Up to Main Lab Page Previous Lesson - Working with Functions Top of this Lesson


Maintained by: P. Danziger, January 1998