Mathematical Institute University of Oxford: Students' Guide Michaelmas Term 2009 Catherine Wilkins

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

MATHEMATICAL INSTITUTE

UNIVERSITY OF OXFORD

Exploring Mathematics with Maple

Students’ Guide
Michaelmas Term 2009
by
Catherine Wilkins
Version 2.3, September 2009, written by Catherine Wilkins

c
°2009 Mathematical Institute, University of Oxford

Acknowledgement to Version 2.3: This course guide has been based in part on Version
1.0 for which many people, in particular Andy Wathen and Brian Stewart, were responsible. I
am grateful to all previous authors and to those who assisted them. Version 2.2, on which this
version is based, represented substantial collaboration with colleagues at The Open University,
most notably Derek Richards and Paul Upton, and their significant contribution is gratefully
acknowledged.
Notes for the 2009/2010 Course

The course will be in two parts: Part I in Michaelmas Term Weeks 3-8 and Hilary Term
Weeks 1-2, and Part II in Hilary Term Weeks 3-8. For Part I you will be allocated a computer
to yourself during scheduled sessions in the Statistics Department, and you may work collabo-
ratively with others in these sessions. None of the work in Part I will be assessed, but instead
will act as a foundation enabling you to work individually during Part II. This individual work
will be assessed and will count towards your Moderations as described in Examination Decrees
& Regulations, 2009 and the current Course Handbook. (See your college tutor if you have any
questions about this aspect of the course.)

The practical sessions will run in fortnightly cycles, each cycle starting on the Monday
of an odd week (starting in week 3, Michaelmas Term). You will be allocated a time to
attend one practical session during each cycle. The practical sessions are held in the Statistics
Department, South Parks Road. During each practical session a demonstrator will be available
for help. Problems are provided for each chapter and you should take some time to prepare for
each practical session by reading the chapter to be covered in advance.

Week Chapter Covered


3-4 MT 1
5-6 MT 2
7-8 MT 3
1-2 HT 4

The above table is only a rough guide. You should work through each chapter in order,
progressing at a rate of roughly one chapter a fortnight. You need to put in concentrated effort
to ensure that you make steady progress and that you finish the course by the end of Week
2, Hilary Term. The material covered in Chapter 4 is particularly important for the projects
that you will work on in Hilary Term Weeks 3-8. However, the material in this manual is
sequential and in order to understand Chapter 4 you will need to have worked methodically
through Chapters 1–3 first.

There are two additional chapters that cover Maple commands, namely Appendices A and
B. The material in Appendix A will be needed for the compulsory first project next term,
and may be worked through at any time after you have finished Chapter 1. Appendix B,
which contains some very useful information on simplifying the output obtained from Maple,
is appropriate any time after Chapter 3. There are certain rules which apply to the use of
computers and these are detailed in Appendix C. A Glossary of commands is provided for you
at the end of this manual, in Appendix D.

The course director for this academic year is Dr Catherine Wilkins. The course demon-
strators (who will be in attendance during each practical session) should be able to answer any of
your questions; alternatively Dr Wilkins can be contacted by email at wilkins@maths.ox.ac.uk.
Contents

1 Introduction to the system and to Maple 1


1.1 Introduction to the Statistics Department system . . . . . . . . . . . . . . . . . 1
1.1.1 Customizing Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2 Saving and opening Worksheets . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.3 Finishing Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Using Maple’s built-in help system . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Introduction to Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.1 General ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.3 Elementary functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 Simple 2D graphs with the plot command . . . . . . . . . . . . . . . . . . . . 11
1.4.1 Simple line graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4.2 Parametric and polar plots . . . . . . . . . . . . . . . . . . . . . . . . . 13

2 Evaluating, solving and an introduction to calculus 14


2.1 The eval family . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.1 eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.2 evalf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.1.3 evalc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2 The solve family . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.1 The solve command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.2 The fsolve command . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3 Differentiation and the diff command . . . . . . . . . . . . . . . . . . . . . . . 21
2.3.1 Differentiation of arbitrary functions . . . . . . . . . . . . . . . . . . . . 23
2.4 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.1 The int and Int operators . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4.2 Numerical evaluation of integrals . . . . . . . . . . . . . . . . . . . . . . 26

3 More Maple commands 29


3.1 Solving ordinary differential equations using dsolve . . . . . . . . . . . . . . . 29
3.2 Solving recurrence relations with rsolve . . . . . . . . . . . . . . . . . . . . . . 31
3.3 Sums and products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 Using Maple to evaluate limits . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.5 Functions in Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.6 Sets and lists in Maple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.6.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

2
3

4 Loops, conditionals and procedures 38


4.1 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.1.1 Approximate solutions to equations . . . . . . . . . . . . . . . . . . . . 40
4.2 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4 Further examples of procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.4.1 Finding the arithmetic mean of a set of numbers . . . . . . . . . . . . . 44
4.4.2 Taylor’s theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.4.3 Euler’s method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.4.4 Euclid’s algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.4.5 A simple matrix procedure . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.5 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.6 Further exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

A Matrix and Vector Algebra 49


A.1 Vector definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
A.2 Matrix definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
A.3 Rows, columns and submatrices . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
A.4 Vector algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
A.5 Matrix algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
A.6 Eigenvalues and eigenvectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
A.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

B Simplification 54
B.1 expand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
B.2 factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
B.3 simplify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
B.4 combine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

C Miscellaneous 59
C.1 University ICTC Regulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
C.2 Plagiarism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

D Glossary of commands 61
Chapter 1

Introduction to the system and to


Maple

In this chapter you will learn about:

• customizing Maple;
• Maple Worksheets - saving and opening them;
• using the Maple help system;
• using Maple as a calculator;
• Maple variables, constants and functions;
• plotting simple line graphs.

1.1 Introduction to the Statistics Department system


Before you start work on Maple, you should ensure that you can log on to the computers in
the Statistics Department and open Maple successfully. Details of how to do this are provided
in a separate handout, and are also found at

http://www.stats.ox.ac.uk/about us/it information/restrictedaccess/


undergraduate maple server

(This address, which can only be accessed from within the University network, should be typed
in as one single long line.)

1.1.1 Customizing Maple


When you start Maple for the first time it will open with the Statistics Department’s default
settings. In this First Year Maple course we want to make sure that you all use the same
settings (where they are important) and that these are the settings needed for the projects in
Hilary Term. You therefore need to make a few adjustments to the default settings at the start
of your very first Maple session; after that they will become your defaults and you will not
need to change them again. (If you plan to use Maple in college or at home then you will also
have to make these changes on your computer(s) there.)

1
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 2

Maple Worksheets and Maple Documents


Maple allows you to work on two different sorts of document.
Documents One sort is called a Document. These are very flexible, and allow the user
to have a wide range of interactions with the formulas in the document. This is great for
experimentation, but less easy to describe and less easy to control.
Worksheets The other sort is called a Worksheet. It is far easier to work systematically on
these, as the input and the output are more clearly separated.

This manual is written in terms of Worksheets, and the project work next term
must be submitted as Worksheets.

By default the Maple system on the Statistics Department’s machines opens with a new blank
Document. You need to change the default settings so that a new blank Worksheet is opened
each time you start Maple (or whenever you click on the ’Create a new file’ button). On
the tool bar at the top of your screen go to Tools...Options and under the Interface
tab choose Worksheet for the category Default Format for new worksheets. Apply this
Globally using the button at the bottom of the pop-up.
(If for some reason you don’t want to make this global change then you can always open a new
Worksheet each time you want one by using the File menu and then choosing New followed by
Worksheet Mode.)

Input and Output


Maple accepts input either as Maple Notation or as 2-D Maths Notation. Although 2-D
Maths Notation looks nicer, it is not always clear what keystrokes are necessary to achieve
the input.

This manual is written using Maple Notation, and this is the input form required
for the projects next term.

The Statistics Department system is configured so that the default is 2-D Maths Notation
and this therefore needs to be changed too. From the toolbar go to Tools...Options, then
under the Display tab choose Maple Notation for Input Display. Then Apply this change
Globally as before.
The same choices are available for output, but there is no reason to change from the default
2-D Maths Notation and so you should leave this setting as it is.
That completes the customization of Maple.

1.1.2 Saving and opening Worksheets


This subsection is not important when you are working through this chapter for this first time.
It is placed here for completeness and will become useful as you progress through the manual.
So either skim-read it now, or leave it out altogether and come back to it later when you need
it. The next subsection, Section 1.1.3, is important now and should be worked through.
You are advised to save the Worksheets that you produce as you work through this manual,
perhaps saving one for each main section covered (Section 1.3, Section 1.4, etc.). Then you will
be able to access the material later on if you need to (this will be very important next term
when you work through the projects). To save a worksheet, choose the Save command on the
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 3

File drop-down menu (or click the ‘Save the active worksheet’ button on the toolbar). If the
worksheet has been saved previously, it will be saved under the existing name. Otherwise, you
will be presented with a file browser and asked to choose a file name. Note that Maple will
append to the filename the ending .mw to denote the fact that it is a Maple worksheet, and not
some other kind of file. The first section you are advised to save is Section 1.3 and you will be
prompted to do so at the end of that section.
To open an existing worksheet, choose the Open command on the File menu (or click the
‘Open an existing worksheet’ icon). You will again be presented with a file browser and asked
to choose the file. When Maple then opens the worksheet, it puts you at the point you were
at when you saved the worksheet. However, it does not carry out any of the assignments in
the worksheet (you will understand what this means after working through Section 1.3). To
get it to do this, click the mouse onto one of the Maple assignments (which will usually be
highlighted in red) and then hit Return. Maple will execute the assignment and any others
within the same ‘execution group’ (as shown by the square bracket on the left-hand side of the
worksheet), and will leave the cursor at the beginning of the next Maple command.

1.1.3 Finishing Maple


Pull down the File menu, and choose Exit. Do this now, so that the changes made above
in Section 1.1.1 can be implemented. Then re-open Maple so that you can continue working
through this manual.

1.2 Using Maple’s built-in help system


Before we introduce you to Maple properly, we just want to draw your attention to Maple’s
extensive and comprehensive built-in help system. One way of accessing this is via the Help
menu on the toolbar and another is by typing a question mark ? at the Maple prompt, followed
by the command you want help with. Say you wanted to search for help on the command
‘solve’. At the prompt type ?solve to bring up a new window with information on solve.
Try it now. The scroll bar on the right hand side of the window can be used to move up and
down the information. You will probably find the first half of each help page largely irrelevant.
The most useful part will be the lower half of the page where examples are given and related
commands are shown. Often it is helpful to cut and paste and edit these examples. One of the
most important functions of the help pages is to indicate exactly what arguments the command
should be supplied with.
Throughout this course you will be encouraged to use Maple’s help facility to learn more about
the commands you are introduced to. You will be asked to access various help pages at several
stages in this manual, but you should do so at any stage if the workings of any particular
command are unclear to you.

1.3 Introduction to Maple


Finally we introduce Maple, which is one of a number of algebraic computing systems. It can

be used as a basic calculator, for example to evaluate ln 3 or 2 to any number of decimal
places (within reason), but its great strength is its ability to manipulate algebraic expressions.
Maple can be used to solve algebraic equations, manipulate matrices and vectors, factorise
polynomials and simplify rational expressions. It knows about complex numbers and it can
also perform many of the standard operations of analysis such as evaluating limits, derivatives
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 4

and integrals. It has very good 2D and 3D graphics facilities so that, for example, solutions of
ordinary differential equations can be found and plotted. It is also a programming language
and, by writing and executing Maple programs, quite complicated operations can be carried
out.
This Michaelmas Term course introduces you to several of these features of Maple and it sets
the scene for many more. First you will learn how to input simple expressions into Maple.
You will then look at how to plot simple 2D line graphs and how to solve certain equations
both symbolically and numerically. You will then be introduced to some of the basic calculus
facilities of Maple and you will see how to differentiate and integrate expressions. You will also
learn how to use Maple to solve ordinary differential equations and simple recurrence relations,
as well as how to evaluate sums and limits. In the final chapter of this manual you will be
introduced to some of Maple’s programming facilities.
Although this manual appears to introduce a lot of Maple commands many, such as plot, sum,
diff and int, are almost self-explanatory. A list of the most common commands, giving more
information, is contained in the Glossary of commands in Appendix D, and you are encouraged
also to use the Maple ‘help’ facility as explained in Section 1.2. In order to become technically
adept at applying Maple, it is important that you attempt all the exercises contained in this
manual (except those marked as optional); remember, Maple is best learned by actually using
it to do mathematics, and this should be practised as often as possible. Try to incorporate
Maple into your weekly problem sheets, perhaps using it to check some of your hand-written
answers.
In this section we will give a brief introduction to Maple, outlining some of its basic features
and illustrating them with some short examples. It is assumed that you have read Sections 1.1
and 1.2, customized your settings as explained in Section 1.1.1, and have an open Worksheet in
front of you. You will need to type in all the commands that you see in this, and subsequent,
chapters; in this way you will become increasingly familiar with the basic ideas.

1.3.1 General ideas


As a start, note that in Maple the prompt is the symbol >. Commands are entered to the
right of the prompt, with each command ending with either a colon or a semi-colon. If
a colon is used, the command is executed but the output is not printed, whereas when a
semi-colon is used the output is printed. Once you have finished typing a command line
then the return/enter key should be pressed. To illustrate this try the following. At the
prompt, type 12/15; followed by the return/enter key. You should see
> 12/15;
4
5
However, typing
> 12/15:

suppresses the output so that no output is seen (this is useful, for example, if the output is
extensive and not specifically required). If you forget the colon/semi-colon Maple will issue
a warning, and the easiest thing to do now is to move the cursor back to the end of the line
just typed (using the mouse or the arrow keys) and add the colon/semi-colon in. Pressing
return/enter should then enable the command to be executed, and will remove the warning;
there is no need to delete it.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 5

To see some more commands, try


> 3+18;
21
> 40*21;
840
> 3!;
6
In the next example, you should only press the return/enter key after typing in the whole
line:
> 2^3; exp(2); sin(Pi); cos(3*Pi/4);
8
e2
0

2

2
The final example above illustrates some important information:

• Many commands can be put on a single line provided that each ends with its own
colon/semi-colon.

• Maple is case-sensitive and Pi with a capital P represents the number 3.141592653 . . .


(more of this in a moment).

• Finally note that multiplication must be made explicit with the * symbol so that 3π is
input as 3*Pi; powers are input via the ^ symbol as shown for 23 above.

You should also observe in the above examples


√ that Maple uses exact arithmetic, giving
exact answers wherever possible (so that 2 is not evaluated to a number, for example).
If decimal approximations are wanted then in certain circumstances Maple can be forced
to produce them by including at least one decimal point in the input, as illustrated in the
following examples1 :
> sqrt(2.0);
1.414213562
> 22/7.0;
3.142857143
However, note that including a decimal point in the input does not guarantee a decimal output
(try typing 3.0*Pi at the prompt, for example). In Section 2.1.2 you will be introduced to the
evalf command which will always return an output in decimal form.

Exercise 1.1
Use Maple to evaluate the following exactly:
3 26
19 × 99, 320 , 21000 , 25!, − .
13 27
1
These decimal numbers are given to ten significant figures, which is the default setting in Maple. You will
see shortly how to alter this.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 6

Now evaluate the following to ten significant figures (and remember that you may need to
include a decimal point in the input):
21 1
, 171/4 , , 0.216100 .
23 99!
Note that the last two answers are so small that Maple gives them in ‘floating-point’ form. ¤

As you saw above with Pi, Maple has some names reserved for constants. The list of these is
short,2 and the ones that you should be aware of now are shown in the Table below.
Pi 3.1415 . . .

I −1
infinity ∞

Missing from this table, as there is no special symbol for it, is the number e, that is exp(1)
or 2.7182 . . .. You should not be tempted to input e or E as Maple will not recognise either
of these. However, typing exp(1) at the prompt gives the output
> exp(1);
e
where the e produced by Maple does indeed mean 2.7182 . . . (try typing exp(1.0) at the prompt
to see what happens). Within Maple, you should be careful not to confuse the e in bold above,
which when output denotes exp(1), with the letter e in italics which has no particular meaning.
Now work through the following exercise which uses the constant I.
Exercise 1.2
As shown above, Maple denotes the square root of −1 by I. Suppose that we wish to express
(2 + 3i)4 in the form a + bi, where a and b are real. The easiest way of achieving this is by
typing
> (2+3*I)^4;
−119 − 120 I
Use Maple to express the following in the form a + bi:
µ ¶4
2 −1 1+i 4 2i
(5 − 8i) , i , and + .
5 + 2i 3 5
¤

1.3.2 Variables
Variables in Maple are denoted by sequences of letters, digits and underscores (with the excep-
tion that a variable may not begin with a digit). For example
x, f, a1, B2, initial conditions
are all legitimate variables (remember that Maple is case-sensitive, so a1 and A1 are different
variables). There are a few words that are reserved by Maple and so cannot be used for
variable names3 . You have already seen Pi, which is one, and for and while are others,
2
type ?constant at the prompt for further information.
3
For more information about reserved names type ?reserved at the prompt.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 7

because these are needed for certain Maple operations (many of which you will learn about
throughout this course).
Variables can be either free or assigned . A free variable is one which has no value associated
with it, whereas an assigned variable takes a particular value (which might be a number, or
a more complicated expression). To assign a value to a variable use the assignment operator
:=, that is, a colon followed by an equals sign. Hence A := B (followed by the usual colon
or semi-colon and then the return/enter key) will assign to A the value of B. So typing
> a:=20;
a := 20
assigns the value 20 to the variable a. This can be checked by asking Maple what value a
takes, which is done simply by typing a followed by a semi-colon, as illustrated here:

> a;
20
Note that there is a direction implicit in assignment; typing 20 := a does not assign the
value 20 to the variable a.
Extending this example, assign b the value a+3 as follows:

> b:=a+3;
b := 23
Maple already knows that a has the value 20 and so has evaluated a+3 directly as 23.
Assignments can be over-written and Maple will only remember the most recent one that
it has been asked to execute. So b, which above took the value a+3, can now be assigned
the value 10 (say) as follows:

> b:=10:
> b;
10

Warning: A frequent mistake in Maple is to attempt to use the equals sign = for assignment
purposes, rather than the assignment operator :=. It is essential to use := when assigning
an expression to a name.4
The following illustration of assignment concerns the reserved variable Digits5 , which con-
trols the number of digits displayed as output and used in computation. The default value
of Digits is 10 but this can be changed using the assignment operator, as shown here:

> 22/7.0;
3.142857143
> Digits;
10
> Digits:=20;
Digits := 20
4
Uses of = in Maple will be illustrated later on in the course.
5
The capital D is important here; digits is just a free variable.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 8

> 22/7.0;
3.1428571428571428571
To check your understanding of assigning variables, try the following exercises.
Exercise 1.3
Assign to a the value 10, to b the value 20 and to c the value a+2*b. Then use Maple to
evaluate a+b+c. ¤

Exercise 1.4
All rational numbers p/q, where p and q are integers (q 6= 0), have a terminating or (eventually)
repeating decimal form. By increasing the number of Digits as appropriate, find the exact
decimal form of 21/23. ¤

Exercise 1.5
Consider the following series of commands. After inputting them all as shown, what would
the final line (that is z;) give as output? (Try to work this out before inputting the com-
mands yourself!)

> a:=3; b:=2;


a := 3
b := 2
> # In the following line the output is deliberately suppressed
> z:=a^2+b^2+x^2:
> a:=4;
a := 4
> z;
¤

Exercise 1.5 illustrates the use of one other new symbol, #. Maple will ignore everything after
this symbol, until the start of the next line. It helps to keep track of things if you put in lines of
explanation like this from time to time; this will become particularly important when writing
the longer procedures that will be encountered later in the course.
You may be wondering how to remove assignments to variable names. The easiest way to do
this is to type restart: or restart; (both have the same effect) at the prompt; this will
reset everything 6 and enable you to start again from scratch. This is always an option if the
expected output is not forthcoming; going back to the start of a sequence of command lines
and adding in restart: before the first command might work wonders. Indeed, it is strongly
recommended that you start all exercises and worksheets with restart:. However, do bear in
mind that restart: removes the effect of any previous output and so it should be used with
caution.

1.3.3 Elementary functions


Maple has many in-built functions, most of which are fairly obvious. Several have already
been introduced, for example:
6
restart: will reset Digits to 10, for example.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 9

> cos(3*Pi/4); sqrt(2.0);


exp(5);

2

2
1.414213562
e5
Note that, as you have already seen, where possible Maple will produce exact answers unless
you request an output value in decimals by including a decimal point in the input.
For the moment, the functions that you should be familiar with are those in the table below.7
(In each case the function needs to be followed by an argument in brackets, as illustrated in
the examples above.)

cos, cosh cosine and hyperbolic cosine


sin, sinh sine and hyperbolic sine
tan, tanh tangent and hyperbolic tangent
sec, sech secant and hyperbolic secant
csc, csch cosecant and hyperbolic cosecant
cot, coth cotangent and hyperbolic cotangent
exp exponential
ln or log natural logarithm
log10 logarithm to base 10
abs absolute value
sqrt square root

Before you practise these, here are some more examples.


> (sin(Pi/4))^2; sin(Pi/4)^2; (sin(3))^2;
1
2
1
2
sin(3)2

> exp(2); ln(%);


e2
2
> abs ( -3);
3
In the above examples you should note the following:
• Maple’s notation for sin2 (x) (and indeed sin3 (x), cos2 (x), e.t.c.) is potentially misleading.
When Maple outputs sin(3)^2 in the example above, it means sin2 3, that is (sin 3)2 ,
7
Remember that help with any of these commands may be found by typing ? followed by the command; for
example, ?abs will give you more information on the abs command.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 10

and not sin(32 ). Similarly, sin(x)^2 or (sin(x))^2 is used to input sin2 x; sin^2x would
not be accepted as input.

• The symbol %, known as the ‘ditto operator’, represents ‘the value of the expression most
recently evaluated’. You should use it with great care but it can be helpful. It is better
practice, however, to assign the output a name, and then to use this name in subsequent
work, as illustrated by the following: ans:=exp(2); ln(ans);.

• Within reason, Maple is forgiving in allowing spaces, as illustrated in the final example
above. However, it would not have evaluated ab s(-3), for example.

To gain a little more practice with functions, try the following exercises.
Exercise 1.6
Use Maple to evaluate the following:

tan(π/3), cos2 (π/3), sec(π/6), 1 + cot2 (π/4), cosec2 (π/4).

Evaluate the following, giving numerical answers to ten significant figures where appropriate:
r q

3 + 3 + 3, e3 ln 4 .

Exercise 1.7
The binomial coefficient n Cr is evaluated in Maple using binomial(n,r). Use Maple to evaluate
10 C and 250 C . ¤
4 12

Exercise 1.8
Use the Maple help facilities to find out how to evaluate arcsin(1/2). Evaluate sec(arctan x) in
terms of x. ¤

Before finishing this section, we would like you to save your Worksheet, as described in Sec-
tion 1.1.2. A filename such as Section1point2 would be sensible; remember that Maple will
append the ending .mw to denote the fact that this is a Maple Worksheet. You will then need
to open a new Worksheet (as described in Section 1.1.2) when you start Section 1.4. From now
on, try to organize your Maple work into Worksheets so that you can easily access the material
you have covered as and when you need to. This will prove particularly helpful next term when
you come to work through the projects.
That ends this first section on Maple. Before proceeding any further, you should take stock
and make sure that you are happy with everything covered so far. In particular, you should
feel confident using the material in the tables on pages 6 and 9 as well as the following: :, ;,
:=, restart, %, # and Digits. The rest of this course will build on these commands and so it
is essential that you understand them.

You may by now have come to the end of your first two hour practical session, in which case
you should try to work through Section 1.4 in your own time (or, if you are unable to do
this, you should resume your next scheduled session in the Statistics Department with Sec-
tion 1.4). However, if you do still have some time left now then you should continue straight
on. Section 1.4 is a brief introduction to Maple’s powerful graphics facilities.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 11

1.4 Simple 2D graphs with the plot command


One of the very useful features of Maple is the ease with which many different types of graphs
may be drawn. This term we will introduce you to the basic commands and next term, if
you wish, you may explore Maple’s graphics packages further. Most graphs are drawn with
variants of the plot command, which has several forms, each with many optional arguments
that determine the appearance of the resulting graph. The simplest of these forms, with a few
of the more important options, is introduced in this section; if at any time you wish to see a
list of available options then type ?plot/options at the prompt to access the relevant help
pages.

1.4.1 Simple line graphs


The simplest graphs are those of functions of a single real variable; for example, the graph
of the function sin(10/(1 + x2 )) for 0 ≤ x ≤ 10 is given by the command8
> plot(sin(10/(1+x^2)),x=0..10);

To save space, the output from the above command is not reproduced here. However, you
should see the graph on your screen, and it should be red, which is the default colour.
The first argument in this command is the formula for the function and the second is the
range of x9 ; if we needed the graph for 10 ≤ x ≤ 100 then we would replace x=0..10 by
x=10..100. On the other hand, the command plot(sin(10/(1+x^2)),x); plots the graph
over the default range −10 ≤ x ≤ 10.
The range of the vertical axis can also be specified; if we only wanted to see the values of
sin(10/(1 + x2 )) in the range 0 ≤ y ≤ 1 then we would use the command
> plot(sin(10/(1+x^2)),x=0..10,0..1);

Exercise 1.9
Assign the expression sin(10 cos x) to the variable y and use the command plot(y,x=-Pi..Pi);
to draw the graph of this function on the interval [−π, π]. ¤

The colour of a graph is changed using an optional argument of the plot command. For
example, the graph of y = sin(10 sin x) for 0 ≤ x ≤ π is drawn in blue with the command
plot(sin(10*sin(x)),x=0..Pi,colour=blue); . (Note that the order of these commands
is important; the range of x values must come before optional commands such as colour.)
For a full list of colours that are predefined in Maple type ?plot,color10 at the prompt.
One of the more useful features of the plot command is the ability to draw graphs of many
functions on the same plot. Thus the graphs of sin x and cos x for 0 ≤ x ≤ π can be
compared with the command
> plot([sin(x),cos(x)],x=0..Pi,colour=[coral,turquoise]);

Here the two functions are inserted as the list11 [sin(x),cos(x)] – the enclosing square
brackets are important. Also we have used the colour option in the form colour=[coral,turquoise]
where again the square brackets are essential and the colour order matches the function or-
der. (It is not necessary to define colours when plotting two or more graphs, because Maple
8
The ‘..’ in x=0..10 is input by typing two successive full stops.
9
The word range here is a Maple term; it does not have the usual meaning of a the range of a function in
mathematics.
10
Note the use of American spelling here – typing ?plot/colour will take you to a list of options from which
you can choose ?plot,color.
11
You will meet lists in Section 3.6.2.
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 12

will automatically plot each curve in a different colour, but you may prefer to do so.) A
legend can be added to the plot with the legend option as in the following example; note
here that not only is the order of the items in the legend important, as always, but use of
the quotation marks is essential.
> plot([sin(x),cos(x)],x=0..Pi,colour=[red,gold],legend=["sin x","cos x"]);

Any number of graphs, within reason, can be combined in this manner simply by including
more functions in the list. Thus the command
> plot([x,x^2,x^3],x=0..1,colour=[red,blue,black]);

draws the graphs of y = x (red), y = x2 (blue) and y = x3 (black) for 0 ≤ x ≤ 1 all on the
same plot.
Exercise 1.10
Draw the graphs of the five functions
y1 (x) = 1, y2 (x) = 1 + x, y3 (x) = 1 + x + x2 /2!, y4 (x) = 1 + x + x2 /2! + x3 /3! and
y5 (x) = exp(x) on the same plot for 0 ≤ x ≤ 1. ¤

Simple changes to the presentation of graphs can be made after they have been drawn by
placing the cursor in the vicinity of the figure and clicking the left mouse button. Then new
buttons will appear on the third bar at the top of the worksheet which allow you to make some
changes; you can see what these are by moving the cursor above each item in turn. What you
may find particularly useful is the extreme left-hand box on the bar, which gives the coordinates
of the cursor; this is helpful for finding approximate coordinates of roots or stationary points.
To practise this, try the following exercise.
Exercise 1.11
Find the approximate coordinates of all the real solutions of the nonlinear simultaneous equa-
tions

y = sin x,
y = x3 − 5x2 + 4.

(You will see in Section 2.2.2 how to find numerical solutions to simultaneous equations such
as these.) ¤

Sometimes it is necessary to plot graphs of functions that are undefined at particular points.
For instance, y = tan x is unbounded at x = (n + 1/2)π, n = 0, ±1, ±2, . . .. The plot
command will attempt to draw the graphs of such functions, but without limits on the
vertical axis the scale is usually distorted. Limiting the range of the vertical axis overcomes
this problem but may introduce unwanted vertical lines. For example, try the following
commands:
> plot(tan(x),x=0..7);

> plot(tan(x),x=0..7,-10..10);
These problems are solved with the use of the optional command discont=true included
in the argument list, as illustrated by the following command:
> plot(tan(x),x=0..7,-10..10,discont=true);
CHAPTER 1. INTRODUCTION TO THE SYSTEM AND TO MAPLE 13

Exercise 1.12
Plot the graphs of y = tan x and y = 1/x on the same diagram over the range 0 ≤ x ≤ 15,
using the discont=true option. Use your diagram to find the first five positive roots of the
equation x tan x = 1 correct to one decimal place. ¤

1.4.2 Parametric and polar plots


For a function that is defined parametrically (with x and y as functions of t, say) then the
general syntax plot([x(t),y(t),t=t1..t2]) can be used to plot the graph of y against x
for t from t1 to t2. So the ellipse x = 2 cos t, y = sin t is plotted with the command
> plot([2*cos(t),sin(t),t=0..2*Pi]);

If that doesn’t look much like an ellipse, try the following:


> plot([2*cos(t),sin(t),t=0..2*Pi],scaling=constrained);

Exercise 1.13
The cycloid
x = t − sin t, y = 1 − cos t
is the curve traced out by a point on a wheel as the wheel turns. Plot this curve for 0 ≤ t ≤ 6π.
¤

Polar plots are achieved with the option coords=polar; the general syntax for plotting the
graph of r = f (θ) for θ from a to b is plot([f(theta),theta,theta=a..b],coords=polar);.
This is illustrated by the following command which plots the cardioid r = 1 − cos θ:
> plot([1-cos(theta),theta,theta=0..2*Pi],coords=polar);

Exercise 1.14
Plot (both leaves of) the lemniscate r2 = cos(2θ). ¤

Exercise 1.14 completes this very brief introduction to Maple’s graphics facilities. Once more
you are encouraged to save your Worksheet for future reference. As mentioned earlier, you will
have the opportunity to extend your knowledge of the various plot commands and options in
one of the optional projects next term. In the meantime, in the next chapter the eval and
solve families of commands are introduced.
Chapter 2

Evaluating, solving and an


introduction to calculus

In this chapter you will learn about:

• different ways of evaluating expressions;


• solving equations symbolically and numerically;
• using Maple to differentiate expressions;
• using Maple to evaluate integrals (symbolically and numerically).

2.1 The eval family


In this section three of the evaluation commands that make up the eval family are intro-
duced. The material here is fairly brief; you will be given plenty of opportunity to practise the
commands throughout the rest of the course. We start with eval.

2.1.1 eval
The command eval is used to evaluate expressions. For example, suppose we want to evaluate
the expression
> y:=x^2+3*x-2;

y := x2 + 3 x − 2
at x = 1. This is achieved by using the command
> eval(y,x=1);
2
What is useful about this is that y itself has not changed, as verified by typing
> y;

x2 + 3 x − 2
so that if we now wish to evaluate y at a different value of x then this is easily done.
To obtain some practice on inputting expressions and evaluating them, try the following exer-
cise.

14
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 15

Exercise 2.1
In each of the following, evaluate the expression at the given value.

(i) x3 − 3x2 + 2x − 1, at x = 5;

(ii) sin x cos3 x, at x = π/4;


³ √ ´
(iii) ln u + 1 + u2 − 3 , at u = 2; ¤

To evaluate an expression containing more than one variable, put the variable values in
curly brackets, separated by commas1 . As an example, suppose that we wish to evaluate
r = x2 + y 2 + z 2 at the point (x, y, z) = (1, 2, 3). This is achieved by typing

> r:=x^2+y^2+z^2;
r := x2 + y 2 + z 2
> eval(r,{x=1,y=2,z=3});
14
to give r = 14. Now we move on to what is probably the most frequently-used command in
the eval family, namely evalf.

2.1.2 evalf
The evalf command (evaluate using floating-point arithmetic) is used to evaluate an ex-
pression to a floating-point number, that is, a number rounded to a certain number of
significant figures. The default number of significant figures used is 10 (the default value of
Digits). This may be changed either by re-assigning Digits2 – which will then produce
a global change to all subsequent expressions until it is re-assigned again – or by using an
additional optional argument to evalf, enclosed in square brackets:

> evalf(sqrt(2));
1.414213562
> Digits;
10
> Digits:=20: evalf(sqrt(2));
1.4142135623730950488
> evalf[7](sqrt(2));
1.414214
The [7] placed immediately after evalf shows that sqrt(2) is to be evaluated to 7 significant
figures; note how evalf has rounded conventionally, so that the seventh significant figure, 3,
has been rounded to a 4. An advantage of putting the required number of significant figures
in square brackets in this way is that the value of Digits is unchanged.

1
The curly brackets denote a set; you will learn more about sets in Section 3.6.1.
2
You saw a re-assignment of Digits in Section 1.3.2.
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 16

Exercise 2.2
The following two expressions are both approximations to π that were discovered by the Indian
mathematician Ramanujan (1887–1920):
12 √ √ √
π1 = √ ln((2 2 + 10)(3 + 10))
190
and sr
192
π2 = 92 + .
22
Use the evalf command to find the absolute errors |π1 − π| and |π2 − π|. Hence determine
how good these approximations actually are. ¤

2.1.3 evalc
This section introduces the command evalc (evaluate using complex number arithmetic).
This assumes that all unknown variables in an expression are real and puts a complex num-
ber in the form a + bi, where a and b are real.
3+4i
To set the scene, suppose that we wish to express 5+6i in the form a + bi; this is achieved
by typing

> (3+4*I)/(5+6*I);
39 2
+ I
61 61
You saw examples similar to this in Exercise 1.2 – without the need for evalc, Maple has
3+4i
shown that 5+6i = 39 2
61 + 61 i.
However, in certain circumstances evaluation to the form a + bi has to be forced using
evalc. This is illustrated in the following example, where it is required to express ln(3 + 4i)
in the form a + bi. (Recall that the natural logarithm of a complex number z is defined by
ln z = ln |z| + i arg(z), where |z| is the complex modulus and arg(z) the complex argument.)

> z:=3+4*I;
z := 3 + 4 I
> ln(z);
ln(3 + 4 I)
This is not yet in the desired form, so type
> evalc(ln(z));
4
ln(5) + arctan( ) I
3
to see that ln(3 + 4i) = ln 5 + i arctan(4/3).
Re and Im can be used to extract the real and imaginary parts, respectively, of an expres-
sion, as illustrated in the following example.

> Re((1+3*I)^2); Im((1+3*I)^2);


−8
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 17

6
In this simple example there was no need for evalc, but as above it can be used to force a
required output when necessary:

> z:=(cos(t)+I*sin(t));
z := cos(t) + sin(t) I
> Re(z^4);
<((cos(t) + sin(t) I)4 )
In the above output, the real part of z has not been found. However, typing
> evalc(Re(z^4));

cos(t)4 − 6 cos(t)2 sin(t)2 + sin(t)4


evaluates the real part of (cos t + i sin t)4 as cos4 t − 6 cos2 t sin2 t + sin4 t.3
To check your understanding of evalc, try the following exercises.
Exercise 2.3
De Moivre’s theorem states that

(cos θ + i sin θ)n = cos(nθ) + i sin(nθ)

for all integers n. Use this theorem to find expressions for cos(2θ) and sin(2θ) in terms of cos θ
and sin θ. ¤

Exercise 2.4
If z = 32 ln 2 + i π4 , express ez in the form a + bi. ¤

That completes this introduction to some of the members of the eval family. We now move
on to look at another family of commands, the solve family.

2.2 The solve family


The main aim of this section is to introduce solve and fsolve, two members of the solve
family of commands. You will also learn about the commands assign and unassign.

2.2.1 The solve command


The solve command can be used to rearrange simple algebraic expressions to arrive at a new
expression. For example, the solution of the equation
1 b
=a+ (2.1)
x x
for x can be obtained using Maple as follows:
> eq:=1/x=a+b/x;

1 b
eq := = a +
x x
> solve(eq,x);

3
When using evalc, it is assumed that t is real, as it is an unknown variable. Maple does not usually make
this assumption about unknown variables, but evalc is a special case.
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 18

−1 + b

a
Note the different uses of := and = here; eq is assigned the Maple version of Equation (2.1).
The command solve(eq,x) has solved the equation assigned to eq for the variable x; had we
wanted to solve for b instead then we would have typed solve(eq,b). In general, then, the
syntax for solving one or more equations is solve(S,X) where S is either a single equation or
a set of equations and X is the required variable or set of variables. So suppose that we wish
to solve the simultaneous equations

x + y = 2, − x + 3y = 3.

This is done within Maple as follows:


> eq:={x+y=2,-x+3*y=3}:
> sol:=solve(eq,{x,y});

5 3
sol := {y = , x = }
4 4
(The curly brackets in the input here are essential and denote a set; as mentioned earlier
sets will be discussed in more detail in Section 3.6.1.) A (rather clumsy) verification that
this is correct can be obtained by evaluating eq at the solution point:

> eval(eq,sol);
{3 = 3, 2 = 2}
Note that at this stage the variables x and y have not actually been assigned the values
contained within the solution sol. This is confirmed by typing

> x,y;
x, y
to see that x and y are returned unassigned. If we wished to assign x and y the values given
in the solution then we could do so by typing

> x:=3/4: y:=5/4:


> x,y;
3 5
,
4 4
However, this is clearly long-winded and error prone; a neater way is to use the assign
command as follows:

> restart: eq:={x+y=2,-x+3*y=3}: u:={x,y}:


> sol:=solve(eq,u);
5 3
sol := {y = , x = }
4 4
> assign(sol):
> x,y;
3 5
,
4 4
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 19

To understand what has happened here, type the following:


> restart: assign(a=3);
> a;
3
In this simple example, a has been assigned the value 3 by using the command assign(a=3),
the effect of which is the same as if we had typed a:=3 (except that even with a semi-colon
after it, assign does not output anything). To assign b the value 4 and then c the value b
type
> assign({b=4,c=b});
> b,c;
4, 4
The curly brackets around b=4,c=b are not necessary here, but have been included to be
consistent – this is what happened with sol above; y was assigned the value 54 and x was
assigned the value 43 .
In general, assign(A=B) can be thought of as having the same effect as A:=B, with one big
difference. Once A has been assigned a value then assign as illustrated above cannot be
used on A again; A has to be unassigned first.
To restore A to its unassigned status use the unassign command:
> unassign(’A’);

Here the symbol ’ is the single forward quote, found on the same key as @ on a standard British
keyboard. Its use is essential; type ?unassign for further details. Alternatively, a variable can
be unassigned by re-assigning it to its name, that is by typing A:=’A’: etc. (and again the
single forward quotes are essential).
The following exercises give you some practice in the use of solve and assign.
Exercise 2.5
Find the solutions of the following equations:
(a) x2 − x − 2025 = 0, (b) x3 − 6x2 − 19x + 24 = 0,
(c) 2x4 − 11x3 − 20x2 + 113x + 60 = 0.
(Please be sure to enter the expressions in (b) and (c) carefully; Maple needs to be able to
factorize the polynomials and may not be able to do so if you make a mistake when typing
them in.) ¤

Exercise 2.6
Use the solve command to find the point of intersection, in the (x, y)- plane, of the two lines

ax + by = A, cx + dy = B.

Using assign,
p find an expression for the distance of the point of intersection from the origin,
namely x + y 2 .
2

2.2.2 The fsolve command


The solve command is used for finding symbolic solutions to equations. This may not always
be possible, but nevertheless numerical solutions can usually be found with the very useful
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 20

fsolve command. For example, suppose we wish to solve the equation

sin x = x3 − 5x2 + 4,

and that having plotted the graphs of sin x and x3 − 5x2 + 4 we know that there are three
solutions, at approximately x = −0.90, 0.89 and 4.78 (these approximate solutions were
obtained in Exercise 1.11). To find the negative solution more precisely, type

> fsolve(sin(x)=x^3-5*x^2+4,x=-1..0);
−0.9004002089
The negative solution is x = −0.900 400 208 9 to ten significant figures.4 Note that the range
is specified using the x=-1..0 construction; although this is optional it is always advisable
to assist Maple by giving it a range in which to search for solutions. The other two solutions
of sin x = x3 − 5x2 + 4 can be found by specifying different ranges:

> fsolve(sin(x)=x^3-5*x^2+4,x=0..1);
0.8854364919
> fsolve(sin(x)=x^3-5*x^2+4,x=4..5);
4.781398393
To test your understanding of fsolve, try the following exercises.
Exercise 2.7
Find real solutions of the equation
1
x sin x =
2
for x in the following ranges: (i) 0 < x < 2; (ii) 2 < x < 4; (iii) 6 < x < 7; (iv) 8 < x < 10.
Verify graphically that there are no solutions in the range 4 < x < 6. ¤

Exercise 2.8
In Exercise 1.12 the five real solutions to x tan x = 1 for 0 < x < 15 were found approximately.
Use the fsolve command to find each root correct to six decimal places. ¤

Exercise 2.9
Use plot to find the number and approximate value(s) of the real solution(s) of x3 + 3x2 −
2x + 1 = 0. Then use fsolve to find the solution(s) correct to six decimal places. Use solve
to evaluate any remaining solutions of x3 + 3x2 − 2x + 1 = 0 that fsolve was unable to find.¤

(Note that in Exercise 2.9 one could have used fsolve with the option complex to find all the
solutions of the given polynomial. Try the command fsolve(x^3+3*x^2-2*x+1=0,x,complex)
or type ?fsolve,details at the prompt for more information.)

That completes the work of this section, which was primarily to introduce the commands solve
and fsolve. The solve command is essential if exact symbolic solutions are required, whereas
fsolve is very useful in obtaining approximate numerical solutions to equations. There will
be more opportunities to practise these commands in the remainder of this course. For now
we move on to look at how Maple can be used to solve problems in calculus, starting with
differentiation.
4
The solution is given to ten significant figures because that is the current value of Digits.
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 21

2.3 Differentiation and the diff command


Maple can easily find the derivatives of expressions of one or several variables. In this section
we introduce the diff command, which is the basic differentiation operator for expressions,
and illustrate its use in different situations including finding the coordinates of stationary
points.
The use of diff is best illustrated with some simple examples. The derivative of sin x with
respect to x is found with the command
> diff(sin(x),x);

cos(x)
The general syntax for differentiating an expression expr with respect to a variable var is
diff(expr,var). Hence the derivative of cos y with respect to y is
> diff(cos(y),y);

−sin(y)
x2 +a2
and the derivative of e with respect to x is found with the commands
> z:=exp(x^2+a^2);
2 +a2 )
z := e(x
> d1:=diff(z,x);
2 +a2 )
d1 := 2 x e(x
2 +a2
The second derivative of ex with respect to x is
> diff(d1,x);
2 +a2 ) 2 +a2 )
2 e(x + 4 x2 e(x
and this same result can also be found all in one go by typing
> diff(z,x,x);
2 +a2 ) 2 +a2 )
2 e(x + 4 x2 e(x
or the equivalent

> diff(z,x$2);
2 2 2 2
2 e(x +a ) + 4 x2 e(x +a )
where x$2 is short for x,x (try typing just x$5 at the prompt).
So the fifth derivative of sin(x2 ) is achieved by typing diff(sin(x^2),x,x,x,x,x); or with
the command
> diff(sin(x^2),x$5);

32 cos(x2 ) x5 + 160 sin(x2 ) x3 − 120 cos(x2 ) x

Partial differentiation5 of expressions of more than one variable is performed by a straight-


forward extension of this procedure. For example, consider the expression sin x cos y; then
its second derivatives are found as follows. First define z = sin x cos y:
> z:=sin(x)*cos(y);

z := sin(x) cos(y)
5
This topic may be new to you; it will be covered in lectures this term.
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 22

Then the second derivative ∂ 2 z/∂x2 is given by


> diff(z,x$2);

−sin(x) cos(y)
whilst ∂ 2 z/∂y 2 is found with
> diff(z,y$2);

−sin(x) cos(y)
For the mixed second derivative ∂ 2 z/∂x∂y type
> diff(z,x,y);

−cos(x) sin(y)
and to verify that the order of differentiation does not matter:
> diff(z,y,x);

−cos(x) sin(y)

If we wanted ∂ 5 z/∂x2 ∂y 3 , then we would type


> diff(z,x$2,y$3);

−sin(x) sin(y)
Sometimes it is necessary to find the derivative of an expression at a particular point, rather
than as a function of the independent variable(s). This is achieved with a combination of
the eval and diff commands6 . Thus the value of the first derivative of sin x at x = 1.6 is
given by the single command
> eval(diff(sin(x),x),x=1.6);
−0.02919952230
The following exercises give practice in the diff command and also revise some earlier com-
mands such as solve and plot.
Exercise 2.10
Find µ ¶
d (x2 + 1)4
dx e2x
and evaluate it at x = 1. ¤

Exercise 2.11
Plot the second derivative of x4 /(1 + x2 ) for −5 ≤ x ≤ 5. ¤

Exercise 2.12
Given y = 12x5 − 15x4 + 20x3 − 330x2 + 600x + 2, find the (x, y) coordinates of any stationary
points (that is, those for which y 0 (x) = 0). Use Maple to plot y over a range of x large enough
to include all stationary points. ¤

6
eval was introduced in Section 2.1.1
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 23

Exercise 2.13
If z = ln(x2 + y 2 ) find the value of the constant a such that
µ ¶2 µ ¶2
∂z ∂z
+ = ae−z .
∂x ∂y

2.3.1 Differentiation of arbitrary functions


So far only the derivatives of expressions with an explicit form (in terms of one or more
independent variables) have been found. In this section we look at how to differentiate
arbitrary functions, say y(x) or f (x, y), without first giving them an explicit form. For
example, we might want to find dy/dx (as a function of y and x) given that x2 + y 2 = 3.
The problem is that typing
> diff(y,x);
0
returns 0 (rather than the dy/dx that might have been expected) because Maple does not
know that y depends on x; x and y are free independent variables and are treated as such.
This difficulty has been addressed in Maple by allowing the use of y(x); Maple interprets
this syntax to mean that, for the purposes of differentiation and integration, y(x) depends
on x. Thus we have
> diff(y(x),x);
d
dx y(x)
> diff(y(x),x$2);
d2
dx2
y(x)
and indeed

> diff(z(p),p);
d
dp z(p)
and even
> diff(z(x,y),x);

∂x z(x, y)
Maple interprets the syntax y(x) (or its equivalent in terms of other letters) in a man-
ner consistent with the rules of calculus. With this notation the diff command knows all
the usual rules of differentiation, for instance the addition, multiplication and quotient rules:

> diff(f(x)+g(x),x);
d d
( dx f(x)) + ( dx g(x))

> diff(f(x)*g(x),x);
d d
( dx f(x)) g(x) + f(x) ( dx g(x))
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 24

> diff(f(x)/g(x),x);
d d
dx f(x) f(x) ( dx g(x))

g(x) g(x)2
To illustrate an application of this theory, suppose that we wish to find dy/dx (in terms
of x and y) given that x2 + y 2 = 3. To do this with Maple, first define the given explicit
equation by typing
> eq1 := x^2+y(x)^2=3;

eq1 := x2 + y(x)2 = 3
and then differentiate this equation, assigning the output equation to a new name, eq2:
> eq2 := diff(eq1,x);
d
eq2 := 2 x + 2 y(x) ( dx y(x)) = 0
Finally rearrange this new equation to make dy/dx the subject:
> solve(eq2,diff(y(x),x));
x

y(x)
Hence dy/dx = −x/y.
Now try the following exercises.
Exercise 2.14
Find the derivatives of
³ ´ ³p ´
sin f (x), sin ef (x) , exp 1 + f (x)g(x) .

Exercise 2.15
Use the solve command to find dy/dx (in terms of y and x) given that

x2 + y 2 + 3xy = 0.

That concludes the work on the differential operator diff. In the next section we stay with
calculus and look at integration.

2.4 Integration
Maple can evaluate many integrals symbolically, and it can also provide numerical estimates
of most definite integrals which cannot be evaluated symbolically as well as those that can. In
this section the integration command int is introduced, along with the related Int.

2.4.1 The int and Int operators


The syntax for integrating an expression expr with respect to a variable var is int(expr,var),
2
and this is best explained with a simple example. To integrate the expression xeax with
respect to x type
> int(x*exp(a*x^2),x);
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 25

2
1 e(a x )
2 a
Note that Maple does not include the arbitrary constant of integration.
Definite integrals are input using the x=a..b construction which you have seen before, in plot
and fsolve, for example. So to evaluate the definite integral
Z 1
2
xe5x dx
0

type
> int(x*exp(5*x^2),x=0..1);
1 1 5
− + e
10 10
and to evaluate Z u
dx

0 u−x
type
> int(1/sqrt(u-x),x=0..u);

2 u
(in the x=a..b construction a and b can be variables, numbers, or expressions).
If Maple cannot evaluate an integral then it simply returns it:
> int(x^x,x);
Z
xx dx

At this point you really need to experiment with some integrals just to see what can be done.
Exercise 2.16
Use Maple to integrate the following expressions with respect to x:

(i) ex − 1, (ii) x2 (ax + b)5/2 , (iii) sinh(6x) sinh4 (x), (iv) cosh−6 (x), (v) sin(ln(x)),

where a and b are constants. ¤

Exercise 2.17
Use Maple to evaluate the following expressions symbolically:
Z 1 Z 1 Z ∞
1 2 −1 1
(i) 3
dx, (ii) x tan x dx, (iii) dx. ¤
1/2 1 + x 0 0 (1 + x)(1 + x2 )

From the exercises you have just done you will observe that Maple’s ability to do rather nasty
integrals is impressive, and that it easily evaluates all of the integrals found in elementary
texts as well as most of the indefinite integrals given in standard tables.
Nevertheless one sometimes encounters cases where it is desirable to have Maple return an
integral unevaluated rather than let it attempt to evaluate it symbolically. This is done
using the inert form of the integration command, Int. By inert, we mean that the integral
is not evaluated, it is merely returned as an integral. For example, type
> Int(x^3/(1+x^2),x);
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 26

Z
x3
dx
1 + x2
Note that Maple just returns the integral unevaluated, whereas had the active form int
been used the integral would have been symbolically evaluated. One use of the inert form
Int is when, for clarity, we wish to display evaluated integrals in the way given by the
following example.
> Int(x^3/(1+x^2),x)=int(x^3/(1+x^2),x);
Z
x3 x2 1
dx = − ln(1 + x2 )
1 + x2 2 2
An important use of Int is in numerical integration, as explained in the next section.

2.4.2 Numerical evaluation of integrals


You may be aware that the majority of integrals cannot be evaluated symbolically. If Maple fails
to find a symbolic answer to a definite integral, or if you know that the integral in question
cannot be evaluated in terms of known functions, then it may be necessary to evaluate it
numerically. Maple does this by using the evalf function as illustrated in the following example,
where we try to evaluate Z 1
e−t arcsin(t) dt.
0
First attempt to find a symbolic result by typing
> z:=int(exp(-t)*arcsin(t),t=0..1);
Z 1
z := e(−t) arcsin(t) dt
0
However, Maple just returns the integral, which means that it does not know the answer.
To find the numerical value of the integral simply evaluate z to a floating point number:
> evalf(z);
0.2952205678
Alternatively, to do the whole thing in one go, and to four digit accuracy (say) then type
> evalf[4](Int(exp(-t)*arcsin(t),t=0..1));
0.2952
Note that the use of Int here, as opposed to int, saves Maple the time-consuming futile attempt
at evaluating the integral symbolically before finding the numerical solution.
Exercise 2.18
Use Maple to evaluate the following integrals numerically to six digit accuracy:
Z 1 Z 10 Z 5 ³ ´
x3 1
(i) e dx, (ii) √ dx, (iii) sin ex/2 dx. ¤
0 0 1 + x4 0

That concludes this section on integration; you are now half way through the course. If you
find that you have time to spare in your laboratory session then you might like to work through
Appendix A. Or try the following optional extended exercises.
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 27

Exercise 2.19
In this optional exercise you are going to explore the function sinc x which is defined as

 sin x x 6= 0,
sinc x = x

1 x = 0.

(a) Assign the expression sin(x)/x to the variable f in Maple and then plot f for −30 ≤ x ≤ 30.
(Note that Maple has no problem with plotting sin0 0 . However, you should satisfy yourself that
your graph looks correct at x = 0, given the above definition.)
There are many interesting and unusual properties of the sinc function and you are asked to
investigate two of these properties here.
(b) First, it can be shown that each maximum or minimum of the graph of sinc x corresponds
to a point of intersection of the graphs of sinc x and cos x. Use Maple to illustrate this, by
drawing the graphs of sinc x and cos x on the same plot for −10 ≤ x ≤ 10. Then use fsolve
to find numerical approximations for the x-coordinates of all stationary points of sinc x for
0 < x ≤ 10, and verify that these are indeed where the two graphs that you have just drawn
meet.
(c) Use Maple to evaluate the three integrals
Z ∞ Z ∞ Z ∞
x x x
(i) sinc x dx, (ii) sinc x sinc dx, (iii) sinc x sinc sinc dx.
0 0 3 0 3 5
(Hint: Since f is not assigned a function, but an expression, you might want to use the eval
command for sinc x3 and sinc x5 .)
Z ∞Y 5
What do you think the value of sinc(x/(2k + 1)) dx is? Use Maple to verify your
0 k=0
conjecture. ¤

Exercise 2.20
In this optional exercise you are asked to use Maple to investigate some rational bounds on π.
(a) Verify that
Z 1 4
x (1 − x)4 22
2
dx = − π. (2.2)
0 1+x 7
This is in itself an interesting result, as 22
7 is often used as a rational approximation for π.
However, this result can also be used to obtain bounds on π in the form a/b < π < c/d, where
a, b, c and d are integers.
(b) Verify (without using Maple) that
Z 1 Z 1 Z 1
1 4 4 x4 (1 − x)4
x (1 − x) dx < dx < x4 (1 − x)4 dx.
2 0 0 1 + x2 0
Z 1
(c) Evaluate J = x4 (1 − x)4 dx, and hence deduce that
0

1979 3959
<π< . (2.3)
630 1260
CHAPTER 2. EVALUATING, SOLVING AND AN INTRODUCTION TO CALCULUS 28

This gives rational bounds on π. You can now use Maple to obtain tighter rational bounds, in
the following manner.
It can be shown that the identity (2.2) can be generalized by replacing the powers of 4 by
powers of any integer multiple of 4 in the following manner:
Z 1 4n
x (1 − x)4n
2(n−1) 2
dx = (−1)n (π − Rn ),
0 2 (1 + x )

where n = 1, 2, 3, . . . and Rn is a rational number. (In (2.2) above, n = 1 and R1 = 22/7.)


Maple can verify this for any given n and the corresponding value of Rn can be computed.
Then, following the procedure of parts (ii) and (iii) above, new bounds on π can be found7 .
(d) Use Maple to calculate R5 .
(e) Hence find the upper and lower bounds on π for the case when n = 5. Evaluate these both
as rational numbers and in decimal form, to thirty significant figures. ¤

7
It can be shown that the higher the value of n, the tighter the bounds on π, but this is not considered here.
Chapter 3

More Maple commands

In this chapter you will learn about:

• solving differential equations and recurrence relations;


• sums and limits in Maple;
• defining functions in Maple;
• the use of sets and lists in Maple.

3.1 Solving ordinary differential equations using dsolve


The dsolve command finds closed form solutions of many types of differential equations. Its
syntax is very similar to solve, which you studied in Section 2.2.1. For example, to solve the
homogeneous differential equation
d2 y
−y =0
dx2
type
> dsolve(diff(y(x),x$2)-y(x)=0,y(x));

y(x) = C1 ex + C2 e(−x)
Notice the slightly strange way by which Maple gives the constants of integration; the solution
is y = C1 ex + C2 e−x . The important thing here is that y(x) is input and not just y; this is an
example of Maple differentiating arbitrary functions which was discussed in Section 2.3.1.
Inhomogeneous equations are no different; to solve
dy y
+ = x2
dx x
type
> dsolve(diff(y(x),x)+y(x)/x=x^2,y(x));
x4
+ C1
y(x) = 4
x
3
and the answer is seen to be y = x /4 + c/x.
Maple does not suffer from fatigue when the going gets tough – the solution of
d3 x d2 x dx
3
− 3 2
+3 − x = 16e3t
dt dt dt

29
CHAPTER 3. MORE MAPLE COMMANDS 30

is found by typing
> de:=diff(x(t),t$3)-3*diff(x(t),t$2)+3*diff(x(t),t)-x(t)=16*exp(3*t):
> dsolve(de,x(t));

x(t) = 2 (et )3 + C1 et + C2 et t + C3 et t2
To insert initial and/or boundary conditions into Maple, proceed as in the following examples.
The solution of the boundary value problem

y 00 + 5y 0 + 6y = 0, y(0) = 0, y(1) = 3

is found with the following commands. First define the differential equation by typing
> de:=diff(y(x),x,x)+5*diff(y(x),x)+6*y(x)=0:

and then solve it with


> dsolve({de,y(0)=0,y(1)=3},y(x));

3 e(−2 x) 3 e(−3 x)
y(x) = −
e(−2) − e(−3) e(−2) − e(−3)
Note how the differential equation and boundary conditions are separated by commas and
enclosed in curly brackets.
Now consider the initial value problem

y 00 + 5y 0 + 6y = 0, y(0) = 0, y 0 (0) = 0.

It is solved with the following command (for de already defined above):


> dsolve({de,y(0)=1,D(y)(0)=0},y(x));

y(x) = 3 e(−2 x) − 2 e(−3 x)


In this example the differential operator D is used to define the initial condition y 0 (0) = 0. We
do not have the scope to go into details here, but D is a differentiation command (like diff)
and its use here is to represent a derivative evaluated at a point 1 .
Exercise 3.1
Use Maple to solve the following differential equations:
d2 y dy
(i) 2
+3 + 4y = sin x,
dx dx
dy
(ii) = 3xy, y(0) = 1.
dx
¤

Exercise 3.2
Solve the differential equation y 00 + y = 0, subject to the initial conditions y(0) = a, y 0 (0) = b.
Use assign and eval to assign the result to a variable and then to evaluate the solution at
x = π. ¤

1
Type ?D and ?dsolve for more details about D and its use here.
CHAPTER 3. MORE MAPLE COMMANDS 31

3.2 Solving recurrence relations with rsolve


Recurrence relations are easy to solve using Maple’s rsolve command, which works in much
the same way as dsolve. Consider the sequence defined by

x0 = 0, xn+1 = n + 1 + xn , n = 0, 1, 2, . . . .

To find the nth term xn type


> xn:=rsolve({x(0)=1,x(n+1)=n+1+x(n)},x);
n
xn := −n + (n + 1) ( + 1)
2
and to tidy this up then
> simplify(xn);

1 1
n + n2 + 1
2 2
2
will help. Hence the result xn = n /2 + n/2 + 1 is obtained.
Exercise 3.3
The Fibonacci numbers form a sequence defined by the recurrence relation

u0 = 0, u1 = 1, un = un−1 + un−2 , n = 2, 3, 4, . . . .

Use Maple to find an expression for un and hence verify that u20 = 6765. ¤

3.3 Sums and products


In this section the sum, add, product and mul commands are introduced. We will concentrate
on sum and add, leaving product and mul to be introduced in an exercise at the end of the
section.
Suppose that it is required to evaluate the sum S defined by
10
X 1
S= r = 1 + 2 + 3 + · · · + 9 + 10 = × 10 × 11 = 55.
2
r=1

To find this using the sum command type

> S:=sum(r,r=1..10);
S := 55
The syntax for the sum command is sum(expr,r=a..b), where the first argument expr is
the expression to be summed and the second argument r=a..b shows the variable r running
from a to b (inclusive, incremented by 1). You have already seen the r=a..b construction,
for example in the plot and int commands, although when used with sum the limits a and
b must be integers and the increment is always one.
The add command has a similar structure to sum and produces (thankfully) the same
result:
> A:=add(r,r=1..10);
A := 55
CHAPTER 3. MORE MAPLE COMMANDS 32

Let us now consider a slightly more general case, where the upper limit is replaced by a free
variable, n. Then
n
X 1
S= r = 1 + 2 + 3 + · · · + (n − 1) + n = n(n + 1). (3.1)
2
r=1

Here you will see that the two commands behave quite differently. The sum command yields
the standard result, albeit in a slightly different form2 :
> S:=sum(r,r=1..n);

(n + 1)2 n 1
S := − −
2 2 2
The add command, however, fails:
> A:=add(r,r=1..n);

Error, unable to execute add


The reason for this behaviour is that the sum command is for symbolic summation. It is
used to compute a closed form for an indefinite3 or definite sum. The add command is
used to add up an explicit sequence of numerical values and so will not work for indefinite
sums. Whilst sum can often be used to compute explicit sums (as seen above), it is strongly
recommended that add be used if an explicit sum is needed. Indeed, if asked to evaluate
most simple finite sums using sum, Maple itself will use add to do so! (There are other
differences between sum and add but they are not of concern here. If you are interested in
learning more, type ?sum and scroll down to ‘Comparison of Sum and Add’.)
Infinite sums are evaluated using sum and the Maple symbol for ∞; for example, the infinite
geometric series is found by typing
> sum(a^k,k=1..infinity);
a

a−1
(Note how Maple gives this answer even though we have not specified that |a| < 1; this is an
error in Maple as the sum to infinity is only valid if |a| < 1.)
With infinite sums add will not work; try typing add(a^k,k=1..infinity); and you should
obtain an error message.
Now try the following exercises.
Exercise 3.4
Use Maple to evaluate the following:
10
X 50
X n−1
X ∞
X 1
(i) (r2 + 3r − 2), (ii) i
2, (iii) k
a , (iv) . ¤
k!
r=1 i=1 k=0 k=0

Exercise 3.5
Use Maple to verify that

X ∞
X ∞
X
2 k2 + k − 1 1 π2
(i) = 1, (ii) = 0, (iii) = . ¤
(n + 1)(n + 2) (k + 2)! k2 6
n=1 k=0 k=1
2
You will see in Appendix B how to direct Maple to output the result in the factorized form given in
Equation (3.1).
3
A definite sum is one with an explicit numerical range and an indefinite sum is one that does not have an
explicit numerical range.
CHAPTER 3. MORE MAPLE COMMANDS 33

The evalf command can be used with add to evaluate finite sums numerically. For example,
the sum
100
X 1
k=1
k + k 3/2
can be evaluated with the commands
> add(evalf(1/(k+k^(3/2))),k=1..100);
1.493842552
(Using add(evalf(...)) in this way, rather than evalf(add(...)) is preferable for sums
with many terms, because less memory is required.)
Now try the following exercises.
Exercise 3.6
Find the numerical values of the sums
X 10 √ X100
1
(i) e− k , (ii) √ . ¤
k=1 k=1
k

Exercise 3.7
By embedding one add command within another, evaluate the double sums
10 X
X 10 20
X 10
X
m 1
(i) (2n + 1)e , (ii) .
n2 + ln(22 + m)
m=0 n=0 n=−20 m=−10

That almost concludes this section on the sum and add commands. However, you may be
wondering if there are commands similar to sum and add, but for evaluating products. Maple
does indeed have product and mul, and these are explored in this final exercise:
Exercise 3.8
Assuming that product and mul4 behave in the same way as sum and add respectively, use
Maple to evaluate the following:
10
Y 5
Y
2
(i) r , (ii) (1 − q r ).
r=1 r=1
Q P
Note: If you have not seen it before, denotes a product in the same way as denotes a
sum. For example,
Y5
(r + 2) = 3 × 4 × 5 × 6 × 7 = 2520.
r=1
¤

3.4 Using Maple to evaluate limits


This short section introduces the command limit. Its syntax is fairly self-explanatory; for
example to find
sin x
lim
x→0 x
4
Remember that you can obtain more information by typing ?product and ?mul at the prompt.
CHAPTER 3. MORE MAPLE COMMANDS 34

type
> limit(sin(x)/x,x=0);
1
Left and right limits are also found easily; for example to find

x2 − 4
lim
x→3+ x2 − 5x + 6
use the command
> limit((x^2-4)/(x^2-5*x+6),x=3,right);

Exercise 3.9
Use Maple to evaluate the following limits
µ ¶
tan x − x 1 x
(i) lim , (ii) lim 1 + . ¤
x→0 x − sin x x→∞ x

3.5 Functions in Maple


Up to now we have not defined a function in Maple; we have just used ‘expressions’ such as
y:=x^2+3. Here y is a variable which has been assigned the value x^2+3. We cannot evaluate
y(2) by typing y(2);, for example, as Maple will just see y(2) as a different variable whose
value it does not know.
Functions (in the mathematical sense) are defined using the -> construction, that is a minus
sign followed by the greater than symbol. This is best illustrated with an example. Suppose
we wanted to define the function f such that f (x) = x2 sin x. In Maple this is achieved by
typing
> f:=x->x^2*sin(x);

f := x → x2 sin(x)
From this things like f (π/2) and f (2x) can be evaluated, and df (x)/dx and df (t)/dt can
be found:
> f(Pi/2);

π2
4
> f(2*x);
4 x2 sin(2 x)
> diff(f(x),x);
2 x sin(x) + x2 cos(x)
> diff(f(t),t);
2 t sin(t) + t2 cos(t)
Note that diff always returns an expression (rather than a function, for example). There
is a way around this, using the operator D instead of diff, but we will not go into details
here.
Functions of more than one variable are defined in much the same way, with the variables
CHAPTER 3. MORE MAPLE COMMANDS 35

enclosed in left and right parentheses as illustrated for the function g defined by g(s, t) =
eis (t2 − t + 1):
> g:=(s,t)->exp(I*s)*(t^2-t+1);

g := (s, t) → e(s I) (t2 − t + 1)


> g(Pi,1);
−1
Compositions of functions are achieved with the ‘at’ symbol @, with (f@g)(x) representing
the composition f (g(x)). This is illustrated with the following commands:
> f:=x->x^2-x:
> g:=x->x^3:
> (f@g)(x);

x6 − x3
> (f@f)(t);
(t2 − t)2 − t2 + t
> expand(%);
t4 − 2 t3 + t
(The use of the command expand is explained in Section B.1.)
Exercise 3.10
If f is defined by x → x3 ln((x)2 ) and g is defined by x → 2x3 , what are f 0 (x) and g 0 (x)? Use
eval to obtain an expression for g 0 (f 0 (x)). ¤

Exercise 3.11
For f and g as defined in Exercise 3.10, verify the Chain Rule for the derivative of f (g(x)), ie
that if h(x) = f (g(x)) then h0 (x) = f 0 (g(x))g 0 (x).
Hint: You might find it easier to find expressions for h0 (x) and f 0 (g(x))g 0 (x) separately; then
subtract one from the other and you should obtain zero, although you may need to use simplify
as described in Section B.3 to see this. ¤

3.6 Sets and lists in Maple


In this final section of Chapter 3 we look briefly at how Maple deals with sets and lists.

3.6.1 Sets
A set in Maple takes the form {expr1, expr2, expr3,..., exprn}, in other words it is
a sequence of expressions enclosed in curly brackets. Examples of sets are
> S1:={1,2,3};

S1 := {1, 2, 3}
> S2:={x^2,3*x,2};
S2 := {2, x2 , 3 x}
Note that these are sets in the mathematical sense of the word; order is not important and
repetitions are ignored:
> {1,3,4,1,2,1};
CHAPTER 3. MORE MAPLE COMMANDS 36

{1, 2, 3, 4}
Given two sets A and B, Maple can perform the usual set operations of union A ∪ B,
intersection A ∩ B and difference A \ B. These are illustrated in the following examples.
> A:={1,2,3,4};

A := {1, 2, 3, 4}
> B:={2,4,6,8};
B := {2, 4, 6, 8}
> A union B;
{1, 2, 3, 4, 6, 8}
> A intersect B;
{2, 4}
> A minus B;
{1, 3}
The jth element of the set S is S[j]:
> B[3];
6
You have in fact already seen examples of sets in this manual. For instance, on p. 18 the
commands
> eq:={x+y=2,-x+3*y=3}:
> sol:=solve(eq,{x,y});

5 3
sol := {y = , x = }
4 4
that solved a pair of simultaneous equations used sets for both the input equations and the
output variables.
Exercise 3.12
Use Maple to verify that if X:={1,2,3,5}, Y:={2,3,4} and Z:={1,3} then

X − (Y ∪ Z) = (X − Y ) ∩ (X − Z) and X ∩ (Y ∪ Z) = (X ∩ Y ) ∪ (X ∩ Z).

(Note that Maple will never be able to prove the generality of these results.) ¤

3.6.2 Lists
In Maple, a list takes the form [expr1, expr2, expr3,..., exprn], in other words it is
a sequence of expressions enclosed in square brackets. Here order and repetition are both
important. Examples of lists are
> L1:=[1,2,3,4];

L1 := [1, 2, 3, 4]
> L2:=[1,2,1,3,2];

L2 := [1, 2, 1, 3, 2]
As with sets a specific element can be extracted:
> L2[3];
1
CHAPTER 3. MORE MAPLE COMMANDS 37

and lists can be concatenated using the op command:


> L3:=[op(L1),op(L2)];

L3 := [1, 2, 3, 4, 1, 2, 1, 3, 2]
We can also find out how many elements are in a list:
> nops(L3);
9
You will revisit lists in the next chapter when you look at procedures.
That completes this third chapter of the manual. It has been kept deliberately short so that
if you have fallen behind you have a chance to catch up. Alternatively, if you have time to
spare within your two hour session then you might like to work through some of the material
in Appendices A and B. Or you could proceed directly to Chapter 4.
Chapter 4

Loops, conditionals and procedures

In this chapter you will learn about:

• using Maple loops and conditionals;


• procedures in Maple;
• debugging Maple programs.

In this chapter you will consolidate all you have learned so far and you will also be introduced
to some simple programming techniques. The material here is very important and a lot of it
will be needed in the Hilary Term projects; it is therefore crucial that you start Hilary Term
Week 3 having completed Chapter 4.
As stated at the start of this manual, as well as being a highly effective interactive symbolic
calculator, Maple is also a programming language. By this we mean that, in Maple, a series of
command lines can be written which, when executed, perform a particular task. You have seen
several simple programs already (and hopefully written a few too). In this chapter you will look
at programming in more detail, to develop longer and more structured command sequences.
In particular you will look at some of the main building blocks of programming, namely loops,
conditionals and procedures.

4.1 Loops
Sometimes a Maple command (or a sequence of commands) may need to be executed a
number of times. The Maple for...do...end do; control structure is provided exactly for
this purpose. For example, say we wanted to output the squares of the integers from 12 to
52 . This is achieved with the following command:
> for j from 1 to 5 do j^2 end do;
1
4
9
16
25
The general structure is

for <var> from <expr> to <expr> do <statement sequence> end do;

38
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 39

where var is a variable (j in the example above), expr are expressions (1 and 5 above) and
statement sequence is the expression we want executed (j^2 above).
By default j was incremented by 1 in the above example; a different step size is achieved
with the optional by:
> for j from 1 to 9 by 2 do j^2 end do;
1
9
25
49
81
and the general structure now is

for <var> from <expr> by <expr> to <expr> do <statement sequence> end do;

As another example, this construction can be used (instead of sum) to find the sum of the
cubes of the even integers between 50 and 100 inclusive:
> sumcubes:=0: # set sumcubes to be zero initially
> for i from 50 by 2 to 100 do
> sumcubes:=sumcubes+i^3
> end do: # the colon here prevents intermediate output from the loop
> sumcubes;
12285000
Note in the above example that sumbubes:=sumcubes+i^3 is on its own separate line. As
you type out the command lines in this way you get the message Warning, premature end
of input after entering the line with the beginning of the for loop, and this message keeps
recurring until you enter the line which terminates the loop. To avoid getting this message,
enter the lines as a single execution group using Shift+Enter instead of Enter at the end
of each line:
> sumcubes:=0:
> for i from 50 by 2 to 100 do # now press Shift and Enter

sumcubes:=sumcubes+i^3 # and again


end do: # now press Enter
> sumcubes;
12285000
(Note that the command sumcubes:=sumcubes+i^3 has been slightly indented; this makes
the whole structure easier to read1 .) To check your understanding of loops, try the following
exercises.
Exercise 4.1
Use the for...do...end do structure to output cos(nπ/2) for n = 0, 1, 2, . . . 10. ¤

Exercise 4.2
N
X
Find (2n − 1)2 for N = 5, 6, . . . , 30. ¤
n=1
1
Recall from Section 1.3.3 that Maple ignores any gaps such as this.
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 40

Exercise 4.3
Find in decimal form
100N
X 100N
X
1 1
and
n n2
n=1 n=1
for N = 1, 2, . . . , 10. What happens in each case as N → ∞? ¤

An alternative to the from <expr> by <expr> to <expr> structure involves the use of
while as follows: from <expr> by <expr> while <expr>. As a simple example, the sum
of the cubes of the even integers between 50 and 100 inclusive could have been found with
the commands
> sumcubes:=0:
> for j from 50 by 2 while j<=100

> do

> sumcubes:=sumcubes+j^3
> end do:
> sumcubes;
12285000
(here the expression j<=100 means ‘j is less than or equal to 100’; see the box on p. 42 for
more details).

4.1.1 Approximate solutions to equations


In this section the for..do..end do structure is illustrated by looking at Newton’s method
for finding approximate solutions to equations of the form f (x) = 0.
The process depends on the fact that ‘nice’ functions are ‘approximately linear’(the First Year
course will give some real meaning to this assertion). Starting with a guess at the solution, a,
the equation of the tangent through (a, f (a)) is

y − f (a)
= f 0 (a),
x−a
f (a)
and this cuts the x-axis at â = a − . This is (we hope) a better approximation to the root
f 0 (a)
than a.
Say we want to find an approximate solution to

f (x) = x5 − x1.33 − 1 = 0

and we know that an initial approximation to the solution we are interested in is a = 1.25.
Maple can be used to find a better approximation with the following commands:
> f:=x^5-x^(1.33)-1:
> a:=1.25;
a := 1.25
> a:=a-eval(f,x=a)/eval(diff(f,x),x=a);
a := 1.184458351
If after typing in these commands you return the cursor to the last line and press enter
again you ought to get an even better approximation to the root; indeed, repeating this a
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 41

few times will give better and better approximations.


However, this is a little clumsy and Maple can do all the iterations in one go, so that a
solution is found that is accurate to a required number of significant figures:
> f:=x^5-x^(1.33)-1:
> a:=1.25: b:=0:
> for j from 1 to 100 while abs(b-a)>10^(-8)
> do
> b:=a;
> a:=a-eval(f,x=a)/eval(diff(f,x),x=a);
> end do;
b := 1.25
a := 1.184458351
b := 1.184458351
a := 1.175116829
b := 1.175116829
a := 1.174942010
b := 1.174942010
a := 1.174941950
b := 1.174941950
a := 1.174941950
Can you see what is happening here? If not, ask a demonstrator to explain the commands to
you.
Exercise 4.4
Adapt the example immediately above this exercise to find successive roots to
1
f (x) = 5 − cos(3x) = x,
4
with a starting value of a = 5. Show that the root is 5.24979 to six significant figures. (Hint:
you may need to use eval or evalf to obtain the numerical approximations.) ¤

4.2 Conditionals
The if...end if; construction allows us to choose alternative courses of action during the
execution of a sequence of commands. The general structure is:
if <conditional expression> then
<statement sequence>
elif <conditional expression> then
<statement sequence>
else
<statement sequence>
end if;
where there can be as many elif..thens as needed (including none at all) and else is also
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 42

optional.
Here is a simple example:
> x:=-3;
x := −3
> if x>2 then
> y:=x+1
> elif x>0 and x<=2 then
> y:=x
> else
> y:=x-1
> end if:
> y;
−4
The <conditional expression> mentioned above is a Maple statement which is either true
or false. This will usually be a comparison using one of the items in the following table
= equality
< less than
> greater than
<> not equal to
<= less than or equal to
>= greater than or equal to

or using the logical operators and, or and not (or a combination of both).
You will have the opportunity to practise the if..end if structure in the next section after
you have learned about procedures.

4.3 Procedures
Maple procedures are sets of commands which are needed to be used repeatedly, often with
different parameter values each time. For example, a procedure could be used to define a
function, to return a matrix or a graph, or to perform a particular calculation. The follow-
ing is an example of a simple Maple procedure.

> f2c:=proc(x)
> evalf(5/9*(x-32));
> end proc;
f2c := proc(x) evalf(5/9 ∗ x − 160/9) end proc
(Normally the final output would be suppressed, by replacing end proc; by end proc:.)
This procedure converts a temperature from degrees Fahrenheit to degrees centigrade; if x is
the degrees in Fahrenheit and y the degrees in centigrade then the two are related by
5
y = (x − 32).
9
To find what 100o F is in centigrade just type
> f2c(100);
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 43

37.77777778
to see that the answer is approximately 37.8o C. The beauty of the procedure is that other
centigrade values can be found from their Fahrenheit equivalents very easily:
> f2c(0);
−17.77777778
> f2c(32);
0.
> f2c(80);
26.66666667
Looking back to the command lines making up the procedure, the main points to notice are:

• The procedure starts with procedure name:=proc() and ends with end proc: (or end
proc;), where in the above example the procedure name is f2c.

• The argument of this procedure is x. Procedures may have one or many arguments, or
none at all.

• The value returned by the procedure is the value of the last statement, that is the state-
ment immediately preceding end proc: (or end proc;). This ‘value’ need not be a
number; for example it could be a graph, a matrix or any Maple expression. In the above
example the value returned is 5/9(x − 32) and this is what is obtained for f2c(x) for the
particular x that is input.

Exercise 4.5
Write a Maple procedure called c2f which converts temperatures in degrees centigrade to
degrees Fahrenheit. Check your procedure by evaluating c2f(0) and c2f(37.8). ¤

As another example, say we wanted to use a procedure to define in Maple the function
2
f (x) = y 3 + + cos y, where y = 5 + 2 sin x.
1 + y2
This can be done with the following commands:
> f:=proc(x) local y;
> y:=5+2*sin(x);
> y^3+1/(1+y^2)+cos(y);
> end proc:

The one extra feature here is the local y declaration. What this means is that the value of
y outside the procedure is unchanged (you should check this by assigning y a value before
using the procedure and then checking that its value is unchanged afterwards). In fact,
Maple forces all variables that are only used within the main body of a procedure to be
local variables, so the command local y is optional since y will be taken to be local anyway.
However if you leave the command out then Maple will produce a message Warning, ‘y‘ is
implicitly declared local to procedure ‘f‘ although the procedure will still work.
It is good practice always to identify local variables using the local statement.
Having typed in the procedure f we can now find f at any x value we choose:
> f(0);
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 44

3251
+ cos(5)
26
> evalf(f(0));
125.3221237
> evalf(f(2));
317.8996537
Exercise 4.6
Write a procedure which defines the function f given by
(
x if x ≥ 0,
f (x) =
−x otherwise.

Check your procedure by finding f (2) and f (−3).


Hint: Use the if..end if structure of Section 4.2 within your procedure. ¤

4.4 Further examples of procedures


In this section you will see some more examples of procedures, illustrating some of the wide
variety of problems to which they may be applied. You should make sure that you type out
each procedure and think carefully about how it works; the procedures are quite lengthy and
complicated and it will take time to understand them fully. Each of the examples revises
material from earlier on in the manual, and you are also introduced to a few new commands.

4.4.1 Finding the arithmetic mean of a set of numbers


This section revises the material on lists covered in Section 3.6.2. Say we wanted to find
the arithmetic mean of a dataset given as a list of elements. This could be achieved using
the following procedure:
> mean:=proc(data) local n,s,i;
> n:=nops(data): #checking size of dataset
> if n<2 then
> error "The input must contain at least two values";
> end if;
> s:=0:
> for i from 1 to n do
> s:=s+data[i];
> end do;
> s/n;
> end proc:

Hence mean(L) is a function that returns the mean of the list L:


> mean([1,2,3,4,5,6]);
7
2
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 45

4.4.2 Taylor’s theorem


Taylor’s theorem tells us how well a function which is sufficiently differentiable can be
approximated by polynomials in the neighbourhood of a point. The taylor command in
Maple calculates the Taylor series of a function together with an ‘order’ of the size of the
remainder after the maximum degree polynomial terms which you specify. Thus
> taylor(cos(x),x=0,5);

1 1 4
1 − x2 + x + O(x5 )
2 24
> convert(%,polynom);

1 1 4
1 − x2 + x
2 24
gives the Taylor expansion of cos(x) about zero with the remainder at degree 5. The
convert command gives just the Taylor polynomial without the remainder.
Note that Maple doesn’t guarantee that the approximating polynomial is very effective;
that’s the job of the mathematician. However, we are often fortunate, and here’s a case
where the Taylor polynomials form better and better approximations locally about the
expansion point as their degree increases. The procedure is fairly self-explanatory although
the command seq, used to create a sequence of values, is new to you. Type ?seq at the
prompt for more information.
> taypol:=proc(f,a,maxdegree,left,right) local p,deg,i,x;
> #
> # Plots the function f and its Taylor polynomials about x=a up to and

> # including degree maxdegree for left <= x <= right


> #
> for deg from 0 to maxdegree do
> p[deg]:=convert(taylor(f(x),x=a,deg+1),polynom):
> end do:
> plot({f(x),seq(p[i],i=0..maxdegree)},x=left..right);
> end proc:

For example, try


> f:=x->sin(1/x);
1
f := x → sin( )
x
> taypol(f,0.5,3,0.1,0.7);
Can you tell which curve is which?

4.4.3 Euler’s method


You have seen how dsolve can find analytic solutions to differential equations. However, not
all differential equations have analytic solutions and in such cases approximate solutions may
be computed using numerical methods such as the following.
The Mean Value Theorem, which holds for a wide class of functions, says that y(x+h)−y(x) =
hy 0 (x + θh) for some θ depending on x and h. For suitable functions we can therefore hope that
hy 0 (x) is a reasonable approximation to y(x + h) − y(x). This is the basis of ‘Euler’s method’.
For an equation in the form y 0 (x) = f (x, y(x)) together with an initial condition y(a) = α, say,
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 46

we must first choose a ‘step length’ h which gives discrete values of xi = a+(i−1)h, i = 1, 2, . . ..
Then set y1 = α and compute approximations yi to y(xi ) for i = 2, 3, . . . using

yi = yi−1 + hf (xi−1 , yi−1 ).

Here is a Maple implementation of Euler’s method. It introduces the Maple structure array
as a way of storing xi and yi ; for more details type ?array at the prompt.
> eulers:=proc(f,a,alpha,h,n,abscis,soln) local i;
> #
> # Euler’s method for y=f(x,y), with y(a)=alpha for a <= x <= nh
> # using a step length h
> # The abscissae (x coordinates) are stored in abscis and
> #the solution sequence is stored in soln
> #
> abscis:=array(1..n+1):
> soln:=array(1..n+1):
> abscis[1]:=a:
> soln[1]:=alpha:
> for i from 2 to n+1 do
> soln[i]:=soln[i-1]+h*eval(f,{x=abscis[i-1],y=soln[i-1]}):
> abscis[i]:=a+(i-1)*h:
> end do:
> end proc:
Hence the approximate solution to
dy
= −xy, y(0) = 1
dx
for 0 ≤ x ≤ 1 using a step size h = 0.1 can be plotted as follows:
> f:=-x*y;

f := −x y
> eulers(f,0,1,0.1,10,abscis,soln):
> plot([seq([abscis[i],soln[i]],i=1..11)]);

4.4.4 Euclid’s algorithm


Euclid’s algorithm for finding the greatest common divisor of two natural numbers is es-
sentially based on the observation that if a > b then gcd(a, b) = gcd(a − b, b). Things can
be improved by taking off as much b as possible; by using the trunc command which trun-
cates any number to the next nearest integer towards zero the following elegant procedure
is constructed:
> euclid:=proc(a,b)
> if b=0 then a else euclid(b,a-b*trunc(a/b))
> end if
> end proc:

Note that this procedure calls itself – this is termed recursion and is available in Maple (but
not all programming languages).
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 47

4.4.5 A simple matrix procedure


You will be looking at a more in-depth linear algebra problem with Maple next term, so
we only present a simple example procedure here. It is a procedure to create an n × n
matrix with 0’s on the diagonal, 1’s everywhere below the diagonal and −1’s everywhere
above the diagonal. This example will make more sense if you have already worked through
Appendix A.
> mat:=proc(n) local A,i,j;
> A:=Matrix(n);
> for i from 1 to n do
> for j from 1 to n do
> if i>j then
> A[i,j]:=1
> elif i<j then
> A[i,j]:=-1
> else
> A[i,j]:=0
> end if
> end do
> end do;
> A
> end proc:

To use this procedure you need to load the package LinearAlgebra as explained in Ap-
pendix A:
> with(LinearAlgebra):
> mat(4);
 
0 −1 −1 −1
 1 0 −1 −1 
 
 1 1 0 −1 
1 1 1 0

4.5 Debugging
When you have written a program, you should not be too surprised if it does not work the
first time you try to run it. The program may either crash completely or may give the wrong
answer.

• If the program crashes, you should try to locate the line where it dies. If this is
not self-evident, you should substitute semi-colons for colons to execute commands. The
program will then print out all intermediate calculations which should make it easier to
find the offending line. (This is not true, however, if a program contains procedures;
only the result of the last evaluation of a procedure will be printed irrespective of the use
of colons or semi-colons within the procedure.) You should then try to work out what
is wrong. Remember that the error is very often just above the line with the apparent
CHAPTER 4. LOOPS, CONDITIONALS AND PROCEDURES 48

error2 . Maple’s error messages can help, but they often pinpoint symptoms rather than
identifying their cause.

• If the program runs but gives the wrong answer, it may prove quite difficult to
locate and correct the error. The first thing is to convince yourself that your program
is trying to solve the right problem. You should try to run the program for very simple
cases, and find the simplest case in which it gives the wrong answer. Remove all code
that is not used in that particular calculation; this is relatively easy to do by inserting a
sharp (#) so that Maple ignores everything that follows up to the end of the line. This
will usually make it easier to pinpoint the error.

4.6 Further exercises


These are only for if you really have spare time after studying the procedures of this unit.
Exercise 4.7
Write a procedure that gives the rows of Pascal’s triangle up to and including the nth row for
any given n. ¤

Exercise 4.8
Write a procedure using Determinant() from the LinearAlgebra package to solve any non-
singular 4 × 4 matrix system using Cramer’s rule. (You may need to do a little research to
discover what Cramer’s rule is.) ¤

2
Two common syntax errors that can be difficult to spot, are (a) to forget the colon/semi-colon after the
command, and (b) to type the letter ‘o’ instead of the number zero.
Appendix A

Matrix and Vector Algebra

This appendix may be studied at any time after you have worked through Chapter 1. However
as less explanation is provided here compared with that given for the core material in Chapters
1–4 you might prefer to wait until you feel fairly proficient with Maple. We therefore suggest
that you work through this appendix any time after you have completed Chapter 3. The ma-
terial covered here will be useful for the compulsory first project in Hilary Term.
Maple provides libraries of programs for many of the main mathematical subject areas, in-
cluding linear algebra. The library that you need to use here is LinearAlgebra and the use
of this package will be compulsory in Project 1 next term1 . To use LinearAlgebra, type
with(LinearAlgebra); at the prompt; this will load everything up for you. In this appendix
it is assumed that this command has been issued at the start (and after every restart;) of
your Maple session. When this command is issued with a semi-colon at the end, the list of
names of commands included in the LinearAlgebra package will be displayed. Use the ? help
feature to find out more about each one when necessary (or type with(LinearAlgebra): to
suppress the list if you no longer wish to see it).
You will see that the names for many of the individual commands, such as Transpose, are
quite long. This is because they are intended to be helpful; the lengthy name means that
the function of each command should be fairly clear. If you prefer you can set up aliases for
commands you use frequently; for example the command alias(tr=Transpose); will mean
that you only need to type tr in future if you require Transpose.

A.1 Vector definition


The column vector a = [2, 1, 5, 9]T can be defined in Maple by typing2
> a:=<2,1,5,9>;
 
2
 1 
a := 
 5 

9
To change the third element to the value 7, type
> a[3]:=7;
a3 := 7
1
So please don’t think of using any other linear algebra package (such as the obsolete linalg).
2
The command with(LinearAlgebra): has already been executed.

49
APPENDIX A. MATRIX AND VECTOR ALGEBRA 50

and then check the result by typing


> a;
 
2
 1 
 
 7 
9
To convert this to a row vector you could use the Transpose command, or if you have set
up the alias suggested in the introduction to this chapter then just type tr(a); to achieve
the same result:
> tr(a);

[2, 1, 7, 9]
Alternatively, to input the row vector b = [2, 1, 7, 9] from scratch type
> b:=<2|1|7|9>;

b := [2, 1, 7, 9]
(the | symbol is on the backslash \ key, to the left of z on most keyboards).
Vectors can be defined and initialized in various ways; for example a zero vector can be set
up with the command
> c:=Vector(4);
 
0
 0 
c := 
 0 

0
and then the entries may be input one at a time, as shown at the start of this section. As
another example, try the following command which sets up the row vector [1, 4, 9, 16]:
> d:=Vector(4,orientation=row,i->i^2);

d := [1, 4, 9, 16]

A.2 Matrix definition


Matrices can be built from vectors; for instance the commands
> y1:=<p,q,r>; y2:=<k,l,m>;
 
p
y1 := q 

r
 
k
y2 :=  l 
m

> A:=<y1|y2>;
 
p k
A :=  q l 
r m
will build a 3 × 2 matrix with columns y1 and y2.
APPENDIX A. MATRIX AND VECTOR ALGEBRA 51

Matrices can also be built up row by row:


> Matrix([[1,2,3],[4,5,6]]);
· ¸
1 2 3
4 5 6
More generally, matrices can be defined by something like the following:
> B:=Matrix(2,4,(i,j)->abs(i-j));
· ¸
0 1 2 3
B :=
1 0 1 2

A.3 Rows, columns and submatrices


Suppose that A is a matrix. The rows i to k can be extracted with the command Row(A,i..k);.
This is illustrated by extracting the first row of B defined above:
> Row(B,1..1);

[0, 1, 2, 3]
The command Column(A, i..k) performs a similar function for columns:
> Column(B,2..3);
· ¸ · ¸
1 2
,
0 1
Submatrices are selected by typing SubMatrix(A,i..j,k..l) where i..j denotes the row
indices we want and k..l denotes the column indices:
> SubMatrix(B,1..2,1..3);
· ¸
0 1 2
1 0 1
We can even extract non-consecutive columns or rows:
> SubMatrix(B,1..2,[2,4]);
· ¸
1 3
0 2

A.4 Vector algebra


Vector algebra follows the usual rules. In the following, it is assumed that v1 and v2 are both
vectors of (the same) length n, and s is a scalar.

Maple command Function


v1+v2 Vector addition
s . v1 Scalar multiplication by s
DotProduct(v1,v2) Scalar product of v1 and v2
v1 . v2 Scalar product of v1 and v2 (as above)
CrossProduct(v1,v2) Cross product of v1 and v2 (for n = 3 only)

Take a bit of care with the dot ‘.’ in DotProduct. If it gets too close to an integer then
Maple will treat it as a decimal point and will probably choke. The following commands
illustrate some of the above:
APPENDIX A. MATRIX AND VECTOR ALGEBRA 52

> a:=<1,2,3>; b:=<4,0,-2>;


 
1
a :=  2 
3
 
4
b :=  0 
−2
> 3 . a;
 
3
 6 
9
> DotProduct(a,b);
−2
> a-a;
 
0
 0 
0

A.5 Matrix algebra


As you will be aware, matrix algebra can only be performed on matrices of the right shapes,
and we shall suppose that the operations defined below have a meaning; if the matrices are
the wrong shape Maple will complain. In the following table, A and B are matrices, I is the
identity matrix with the same dimensions as A, v is a vector and s a scalar.

Maple command Function


s . A Scalar multiplication by s
A+B Matrix addition of A and B
A . B Matrix multiplication of A by B
A^n Matrix powers (integer n)
1/A or A^(-1) Matrix inverse (square matrices)
A - s A − sI
A . v Multiplication of A by v
Determinant(A) det(A)
Trace(A) trace(A)
Adjoint(A) adj(A)
Transpose(A) AT

The command A - s above is interesting; in this context Maple knows that A is a matrix and
although s is a scalar it assumes that we want to subtract sI (so that the subtraction is mean-
ingful).
Don’t forget that you can obtain help with these commands by typing ? followed by the com-
mand you are interested in; try ?Adjoint, for example.
APPENDIX A. MATRIX AND VECTOR ALGEBRA 53

A.6 Eigenvalues and eigenvectors


Again it is assumed that A is a matrix, and we now assume that it is also square. The commands
CharacteristicPolynomial(A,x), Eigenvalues(A) and Eigenvectors(A) will provide what
they promise (although you should note that the command Eigenvectors(A) will also produce
the eigenvalues of A for free). Consult the help pages for full details, and see also Exercise 5.3
below.

A.7 Exercises
Working through the following exercises will give you some practice in using the LinearAlgebra
package.
Exercise 5.1  
· ¸ · ¸ 2 5
1 2 3 1 3 7
Let A = ,B= and C =  4 6 .
4 5 6 4 −5 0
−1 0

Use Maple to find (where possible) 3A, A − 2B, A + 2C, AC, CA, AB and AT .
Verify that (AC)T = C T AT . ¤

Exercise 5.2
Consider the set of simultaneous equations

3x + y − z = 1,
5x + y + 2z = 6,
4x − 2y − 3z = 3.

Write this as a system Ax = b, where A is a 3 × 3 matrix, x = [x, y, z]T and b is a column


vector of length 3. Use Maple to invert the matrix A and hence find the solution x to the
simultaneous equations. ¤

Exercise 5.3
(a) Use Maple to find the eigenvalues and corresponding eigenvectors of the matrix
· ¸
2 3
A= .
2 1

(b) Now use Maple to find the eigenvalues and eigenvectors of


(i) A3 , (ii) A−1 , (iii) A − 6I (where I is the 2 × 2 identity matrix), (iv) (A + 3I)−1 .
In each case can you spot the relationship of the eigenvalues and eigenvectors found in (b) to
those found in (a)? ¤
Appendix B

Simplification

This appendix may be studied at any time after Chapter 3.

The main strength of Maple is its ability to manipulate mathematical expressions symbolically.
For example, in this manual you have seen how to differentiate and integrate expressions, how
to evaluate sums, and how to solve equations. This appendix introduces the four commands
expand, factor, simplify and combine that rearrange mathematical expressions. Some of the
examples given here are necessarily rather mundane, so that you gain familiarity with these
new commands, but we also revisit some of the earlier material in this manual to see how the
Maple output may be improved.

The symbolic manipulation of expressions rarely creates results in the form needed by the user.
This is because there are infinitely many ways of writing any expression. A user needs to know
how to persuade Maple to change the form of a particular expression into what is needed. This
is more of an art than a science but a minimum requirement is a working knowledge of the
commands and techniques introduced here. Usually some ingenuity is also required, and plenty
of experience, so the more practice you gain in these important techniques the better.

The fundamental problem is that there are no absolute rules for ‘simplifying’ expressions, nor,
indeed, is there any definition of what it means to ‘simplify’ an expression. For example, cos 2x
might sometimes be better rewritten as 2 cos2 x − 1, or as 1 − 2 sin2 x, or as cos2 x − sin2 x; and
sometimes x3 − y 3 is better as (x − y)(x2 + xy + y 2 ) but sometimes it is better left just as it is.
Algebraic systems such as Maple have to apply fixed rules (for example Maple almost always
replaces sin2 x with 1 − cos2 x) and these rules may conflict with the requirements of the user.

This brief introduction to simplification should enable you to learn enough to start manipulating
the output produced by Maple into forms that are suitable for what you require. We start with
expand.

B.1 expand
The expand command does exactly what its name implies. In this section we will look at
how it works when applied to polynomials and to trigonometric functions.
The effect of expand on polynomial expressions is fairly obvious; for example the expansion
of (x + 1)(x + z)2 is found by typing

54
APPENDIX B. SIMPLIFICATION 55

> expand((x+1)*(x+z)^2);
x3 + 2 x2 z + x z 2 + x2 + 2 x z + z 2
When applied to trigonometric functions expand uses the sum rules1 to remove multiple
angles, replacing them with powers:
> expand(cos(2*x));

2 cos(x)2 − 1
(remember that in Maple cos(x)^2 means cos2 x). So Maple has first expanded cos 2x into
cos2 x − sin2 x and it has then used the rule sin2 x = 1 − cos2 x mentioned in the introduction
to this chapter.
Other examples of the expand command are
> expand(sin(x+y));

sin(x) cos(y) + cos(x) sin(y)

> expand(cos(2*x+y));
2 cos(y) cos(x)2 − cos(y) − 2 sin(y) sin(x) cos(x)

> expand(cos(5*x));
16 cos(x)5 − 20 cos(x)3 + 5 cos(x)
If in the last example above we wished instead to obtain the partial expansion cos 5x =
cos 4x cos x − sin 4x sin x then we would need a little trickery:

> c:=expand(cos(x+y));
c := cos(x) cos(y) − sin(x) sin(y)

> eval(c,y=4*x);
cos(x) cos(4 x) − sin(x) sin(4 x)
Maple will also expand hyperbolic expressions in much the same manner; for example try
> expand(sinh(3*x));

4 sinh(x) cosh(x)2 − sinh(x)


Exercise 6.1
Use Maple to show that

cos(5x) = 16 cos5 x − 20 cos3 x + 5 cos x,


sin(3x) = 4 sin x cos2 x − sin x.

1
cos(x ± y) = cos x cos y ∓ sin x sin y is an example of a sum rule.
APPENDIX B. SIMPLIFICATION 56

B.2 factor
For polynomials the factor command is in some ways the opposite of expand, and once
more it does as one would expect:
> factor(x^5-x^4-7*x^3+x^2+6*x);

x (x − 1) (x − 3) (x + 2) (x + 1)

> f:=x^4+4*x^3*y-7*x^2*y^2-22*x*y^3+24*y^4;
f := x4 + 4 x3 y − 7 x2 y 2 − 22 x y 3 + 24 y 4
> factor(f);
(−y + x) (−2 y + x) (3 y + x) (4 y + x)
In the second example above f has been defined first; this is a useful trick with long
expressions to check that they are typed correctly before proceeding.
The factor command can also be used on rational expressions:
> factor((x^3-y^3)/(x^4-y^4));

x2 + x y + y 2
(y + x) (x2 + y 2 )
(where the common factor (x − y) in the numerator and denominator has been cancelled).
Exercise 6.2
Expand the function f = (x + y + 1)3 and then factorise f − 1. ¤

Exercise 6.3
Use the expand and factor commands to show that
sinh 5x = sinh x(4 cosh2 x + 2 cosh x − 1)(4 cosh2 x − 2 cosh x − 1). ¤

Exercise 6.4
Use Maple to show that
n
X 1
r = n(n + 1),
2
r=1
n
X 1
r2 = n(n + 1)(2n + 1),
6
r=1
n
X 1 2
r3 = n (n + 1)2 .
4
r=1

B.3 simplify
The command simplify is the most general of Maple’s simplification commands and is
usually the one to be tried first. However, it is not always the most appropriate command
and its results can be unpredictable so you are advised to keep a copy of the original
material. Normally, however, it does produce a simpler result, and it does so by applying
APPENDIX B. SIMPLIFICATION 57

certain rules. For example, sin2 x is replaced by 1 − cos2 x, sinh2 x is replaced by cosh2 x − 1
and ux uy is replaced by ux+y . For more information about these rules and others, type
?simplify at the prompt.
Positive integer powers of trigonometric and hyperbolic functions are simplified by these
rules as far as possible, as illustrated by the following attempt to simplify sinh4 x−cosh4 x:
> simplify((sinh(x))^4-(cosh(x))^4);

1 − 2 cosh(x)2
Note that simplify does not convert tan x to sin x/ cos x; this is done using the convert com-
mand that is not covered in this manual2 .
One of the most useful applications of simplify is when trying to verify that expr1 =
expr2, where expr1 and expr2 are both expressions. This is achieved with the command
simplify(expr1-expr2), as illustrated by the following attempt to verify that

1 + tanh2 x
= cosh 2x :
1 − tanh2 x

> expr1 := (1+tanh(x)^2)/(1-tanh(x)^2);


1 + tanh(x)2
expr1 :=
1 − tanh(x)2
> expr2 := cosh(2*x);
expr2 := cosh(2 x)
> simplify(expr1-expr2);
0
The following exercises will give you some practice in the simplify command. You may also
need to use some earlier commands such as solve, eval and diff.
Exercise 6.5
Use the simplify command to show that

1 + sin x dy cos x + sin x + 1


if y= then = ;
1 + cos x dx 1 + 2 cos x + cos2 x
r
1+x dy 1
if y = ln then =− ;
1−x dx −1 + x2
à !
(1 + x)1/2 dy −5 + x
if y = ln then = .
(1 − x)1/3 dx 6(−1 + x2 )

Exercise 6.6
Consider the general cubic polynomial
1
f (x) = ax3 + bx2 + cx + d
3
2
Type ?convert if you want to learn about convert.
APPENDIX B. SIMPLIFICATION 58

where a, b, c and d are real constants. If the stationary points of f are at x1 and x2 , use Maple
to show that
a
f (x1 ) − f (x2 ) = − (x1 − x2 )3 .
6
¤

Exercise 6.7
Show that the function f = 1/r, where r2 = (x − a)2 + (y − b)2 + (z − c)2 and a, b and c are
constants, is a solution of Laplace’s equation

∂2f ∂2f ∂2f


+ + = 0.
∂x2 ∂y 2 ∂z 2
¤

B.4 combine
Whilst you saw in Section B.2 that the factor command is in some ways the opposite of
expand for polynomials, in other circumstances it is more the case that combine performs
this opposite function. The following examples show how it can be used.
> combine(exp(x)*exp(y));

e(x+y)
> combine(x^(p/q)*x^(r/s));
(p+r)
x q s
One of the very useful applications of combine is trigonometric simplification because it
transforms powers of sine and cosine into their multiple angle expansions. For example,

> combine(sin(x)^2);
1 1
− cos(2 x)
2 2

> combine(cos(x)^6);
1 3 15 5
cos(6 x) + cos(4 x) + cos(2 x) +
32 16 32 16

> combine(sin(x)^2*(1-cos(x)^5));
1 3 1 5 1 1
+ cos(5 x) + cos(3 x) − cos(x) − cos(2 x) + cos(7 x)
2 64 64 64 2 64
Exercise 6.8
Use Maple to find multiple angle forms for sin7 x, cos3 x and cosh4 x. ¤
Appendix C

Miscellaneous

C.1 University ICTC Regulations


All use of the computing and network facilities in the Oxford University Computing Services,
as well as all other computing and network facilities throughout the University of Oxford and
associated Colleges, is subject to certain rules. These rules concern what is considered to be
unacceptable behaviour and misuse, as well as what may infringe licence terms or may be
otherwise illegal. Note that all use is permitted for bona fide purposes only, and is subject to
proper authorization (which may be provided either explicitly or implicitly).

The University regards computer misuse as a serious matter which may warrant
disciplinary (or even criminal) proceedings.

The rules by which you have agreed to be bound can be found at the following webpages; it is
your responsibility to familiarize yourself with them:

http://www.admin.ox.ac.uk/statutes/regulations/196-052.shtml
http://www.maths.ox.ac.uk/notices/it/rules/

Misuse of computing and network facilities and unacceptable behaviour include (but are not
limited to) the following:

• Attempting to gain unauthorized access to a facility;

• Using someone else’s username and/or password;

• Giving your password to someone else to use, and/or disclosing your password to someone
else, and/or being otherwise careless with your password;

• Disregarding the privacy of other people’s files;

• Generating messages which appear to originate with someone else, or otherwise attempt-
ing to impersonate someone else;

• Sending messages which are abusive or a nuisance or otherwise distressing;

• Accessing, storing, creating, distributing or displaying offensive or explicit material, es-


pecially in a public place;

• Trying to interfere with someone else’s use of the facilities;

59
APPENDIX C. MISCELLANEOUS 60

• Disregard for ‘computer etiquette’;

• Sending chain email;

• Being wasteful of computer or network resources;

• Software piracy (including infringement of software licences or copyright provisions);

• Using the facilities for commercial gain without explicit authorization;

• Physically damaging or otherwise interfering with facilities.

C.2 Plagiarism
In Michaelmas Term you are encouraged to co-operate with fellow students in learning to use
the system and to use Maple. The Hilary Term projects, however, must be your own unaided
work.
The description of each project gives references to books covering the relevant mathematics; if
you cannot understand some of this then you are free to consult your tutors or others about
it, but not about the project itself. You may discuss with the demonstrators and others the
techniques described in the Michaelmas Term Students’ Guide, and the commands listed in
the Hilary Term Students’ Guide or found in the Maple Help pages. You may ask the course
director to clarify any obscurity in the projects.
The projects must be your own unaided work. You will be asked to make a
declaration to that effect when you submit them.
Appendix D

Glossary of commands

add
Evaluates sums of numerical values; may be used with evalf to obtain a numerical result.
Examples: > add(r,r=1..10); > add(evalf(1/(k+k^(3/2))),k=1..100);

diff
Differentiates an expression with respect to one or more of its variables.
Examples: > diff(x^3+sin(x),x); > diff(x^2*y^3,y); > diff(y^4*sec(x),x$2,y$3);

dsolve
Solves a given ordinary differential equation for an unknown variable.
Example: > dsolve(diff(y(x),x$2)-y(x)=3x^2,y(x));

eval
Evaluates expressions.
Example: > eval(x^2+3,x=1);

evalf
Evaluates an expression using floating-point arithmetic.
Examples: > evalf(ln(2)); > evalf[20](exp(3));

fsolve
Finds approximate numerical solutions to equations.
Examples: fsolve(tanh(x)=x/2,x=0..5); > fsolve(tanh(x)=x/2,x);

61
APPENDIX D. GLOSSARY OF COMMANDS 62

int
Evaluates indefinite or definite integrals symbolically (use with evalf for numerical solutions).
Examples: > int(sin(x),x); > int(exp(u),u=0..2); > evalf(int(exp(x),x=0..2));

Int
The inert form of int; returns integrals unevaluated; also used to evaluate integrals numerically.
Examples: > Int(sin(x),x=0..Pi); > evalf(Int(exp(-t),t=0..4));

limit
Evaluates limits.
Examples: > limit(sin(x)/x,x=0); > limit((x^2-4)/(x^2-5*x+6),x=3,right);

plot
Creates a two-dimensional plot.
Examples: > plot(x,x=0..5);
> plot([sin(x),cos(x)],x=0..Pi,colour=[red,gold],legend=["sin x","cos x"]);
> plot([t,t^2,t=0..2]); > plot([cos(theta),theta,theta=0..2*Pi],coords=polar);

rsolve
Solves recurrence relations.
Example: > rsolve({x(0)=1,x(n+1)=n+1+x(n)},x);

solve
Rearranges expressions to make one or more designated variables the subject.
Examples: > solve(1/x=a+b/x,x); > solve({x+y=2,-x+3*y=3},{x,y});

sum
Evaluates symbolic sums.
Example: > sum(r^2,r=1..n);

You might also like