Maple: A Primer 1643274880, 9781643274881

482 85 7MB

English Pages [171] Year 2021

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Maple: A Primer
 1643274880, 9781643274881

Table of contents :
C
Contents
Preface
Author biography
1 Starting Maple
2 Introductory examples
3 Plotting with Maple
4 Solving equations and systems of equations
5 Using units and physical constants
6 Linear algebra
7 Introduction to calculus
8 Differential equations
9 Procedures
10 Working with external files
11 Regression and statistics

Citation preview

Maple A primer

Maple A primer Bernard V Liengme St Francis Xavier University, Antigonish, Canada

Morgan & Claypool Publishers

Copyright ª 2019 Morgan & Claypool Publishers All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior permission of the publisher, or as expressly permitted by law or under terms agreed with the appropriate rights organization. Multiple copying is permitted in accordance with the terms of licences issued by the Copyright Licensing Agency, the Copyright Clearance Centre and other reproduction rights organizations. Rights & Permissions To obtain permission to re-use copyrighted material from Morgan & Claypool Publishers, please contact [email protected]. Supplementary material to accompany this book is available at http://iopscience.iop.org/book/ 978-1-64327-488-1. ISBN ISBN ISBN

978-1-64327-488-1 (ebook) 978-1-64327-485-0 (print) 978-1-64327-486-7 (mobi)

DOI 10.1088/2053-2571/ab0bb3 Version: 20190501 IOP Concise Physics ISSN 2053-2571 (online) ISSN 2054-7307 (print) A Morgan & Claypool publication as part of IOP Concise Physics Published by Morgan & Claypool Publishers, 1210 Fifth Avenue, Suite 250, San Rafael, CA, 94901, USA IOP Publishing, Temple Circus, Temple Way, Bristol BS1 6HG, UK

To Pauline, my wonderful wife, friend and critic.

Contents Preface

xi

Author biography

xiii

1

Starting Maple

1-1

1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10

What is Maple? The Maple interface Entering simple expressions The use of evalf[d](term) Some handy algebraic commands Context menus Formatted output with printf Data structures Defining a function Debugging a worksheet

2

Introductory examples

2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10

Ammonia Water pump Telescope resolution Velocity of a bullet Solve puzzle Vertex form Classic inclined plane problem Baseball problem Center of mass Trough problem

3

Plotting with Maple

3-1

3.1 3.2 3.3 3.4 3.5 3.6 3.7

Starting with plot Plot tools Customizing with the context menu Customizing a plot with parameters A logarithmic plot Using display for multifunction plots Two plots side by side

3-1 3-1 3-3 3-4 3-7 3-7 3-8

1-1 1-1 1-3 1-7 1-8 1-10 1-12 1-13 1-17 1-18 2-1 2-1 2-1 2-1 2-3 2-3 2-4 2-7 2-8 2-9 2-13

vii

Maple

3-9 3-9 3-9 3-12 3-14 3-18 3-18 3-20 3-20

3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16

Plotting a family of curves Plotting digitalized data Parametric plots Using the coords = polar option Implicit plots Animated plots Exploring with the Explore command Plot with two axes Three-dimensional plots

4

Solving equations and systems of equations

4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10

The solve command Solving inequalities Stress analysis The assign command The fsolve command Systems of equations with fsolve Finding complex roots Restricting the root to a range Example of using isolve Off to Mars

5

Using units and physical constants

5-1

5.1 5.2 5.3 5.4 5.5 5.6 5.7

Some basic examples Examples of usage Using the Units command Temperature conversions Physical constants Gravity constants G and g Pump problem revisited

5-1 5-1 5-3 5-4 5-7 5-7 5-8

6

Linear algebra

6-1

6.1 6.2 6.3 6.4

Matrices and vectors Simple matrix and vector math Linear algebra Solving a system of equations

6-1 6-2 6-2 6-2

4-1 4-1 4-3 4-4 4-5 4-6 4-8 4-8 4-11 4-14 4-15

viii

Maple

6.5 6.6 6.7

Introduction to eigenvectors and eigenvalues Notes on Maple vector commands Some vector calculations

7

Introduction to calculus

7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10

Looking for the limit Some differentiation examples The D operator Implicit differentiation Examples of critical points Some integration examples Definite integrals The assume command Finding the area between two curves Introduction to ODEs

8

Differential equations

8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9

Initial value problems (IVPs) Entering ODEs and initial/boundary conditions Boundary value problems (BVPs) Family of solutions Numerical integration The simple pendulum Coupled ODEs Singular and general solutions Direction fields

9

Procedures

9.1 9.2 9.3 9.4 9.5 9.6 9.7

Programming structures Simple examples Procedures Several ways to find the GCD Further procedure examples Fourier expansion Common errors in procedures

6-8 6-13 6-14 7-1 7-1 7-1 7-5 7-5 7-5 7-6 7-7 7-8 7-9 7-10 8-1 8-1 8-1 8-2 8-4 8-4 8-7 8-10 8-12 8-13 9-1 9-1 9-2 9-2 9-4 9-5 9-10 9-10

ix

Maple

10

Working with external files

10-1

10.1 10.2 10.3 10.4 10.5 10.6 10.7

Export and import a matrix Using fprintf Using readdata Read data from an Excel file Write data to an Excel worksheet The Task Assistant Import Copy and paste

10-1 10-1 10-3 10-3 10-6 10-6 10-9

11

Regression and statistics

11-1

11.1 11.2 11.3 11.4 11.5 11.6

Linear regression Non-linear regression Descriptive statistics Sample or population? Hypothesis testing Combinations and permutations

11-1 11-2 11-3 11-5 11-8 11-11

x

Preface Maple® is a very powerful symbolic mathematics program. We can, for example, input into a Maple document an expression like y: = x2 + 3x − 18 and command Maple to plot this, solve it (i.e. find its roots), find its differential or its integral (antidifferential), etc. Because of its power, Maple has a fairly steep learning curve. The purpose of this small book is to help you climb a little way up that curve. A computer application cannot be mastered by just reading text; it is necessary to ‘get one’s hands dirty.’ The reader is encouraged to download the associated files and experiment with them. You will need to be patient and to carefully look at your work if the outcome is unexpected. For example, the user must remember that a variable (or, to use Mapletalk, a name) is assigned a value or expression using the := operator. It is so easy to forget this and use just =. Maple will not complain but later statements will fail to give the expected results. On a few occasions, the author has had the odd experience of entering a statement that appears to obey the Maple syntax but fails to generate an output; the solution was merely to re-type the statement. It is recommended that all Maple documents begin with the restart command and that the user recalculates the document after editing by clicking the !!! icon (more on this in chapter 1) The Maple on-line help website at https://www.maplesoft.com/support/help/ allows you to search for help. In addition, the site https://www.mapleprimes.com/ connects you to the Maple users’ community; here you can see other users’ solutions or post a question seeking assistance. If you wish to do an Internet search, say to get information on the Maple command plot, use a search term like maple software plot where the inclusion of software decreases the chances of hits about the maple tree or maple syrup. Within the text, a notation such as [Algebra.mw] indicates that a sample file is available for the topic under discussion. Files referenced in the book may be downloaded from either of these sites: (a) The publisher’s site: https://iopscience.iop.org/book/978-1-64327-488-1 (b) The author’s website: https://people.stfx.ca/bliengme/IOP/MapleFiles.zip. To avoid the confusion caused by the use of quotes in computer books, generous use of italics is made. For example, to reference the command used to solve equations, the text might read: ‘The solve command is shown here’. To indicate what one might type in a worksheet, a sans serif font is used, as in: ‘Enter the statement a := b’. Wishing you every success in learning Maple. Bernard V Liengme St. Francis Xavier University Antigonish, Nova Scotia January 2019

xi

Maple

Maple 2017 was used when preparing this text, but it is expected that the files will be compatible with versions back to Maple 2015. They are certainly compatible with Maple 2018.

xii

Author biography Bernard V Liengme Bernard V Liengme is a retired Professor of Chemistry and Lecturer in Information Systems of St. Francis Xavier University in Nova Scotia, Canada, where he taught for over 36 years. He is the author of: A Guide to Microsoft Excel for Business and Management (two editions), and A Guide to Microsoft Excel for Scientists and Engineers (six editions). The latter has been adopted by various engineering schools worldwide. Bernard has been awarded the Microsoft Most Valued Professional award in Excel in each of the last eight years.

xiii

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 1 Starting Maple

1.1 What is Maple? This is how Wikipedia describes the Maple® software: Maple is a symbolic and numeric computing environment and is also a multi-paradigm programming language. Developed by Maplesoft, Maple also covers other aspects of technical computing, including visualization, data analysis, matrix computation, and connectivity. A word on terminology: in websites and books dealing with Maple, you will see references to 1D and 2D mathematics. A 1D expression is one like y:=x^2 + 4 while in 2D it is seen as y:=x. In 1D we could use y:=a*b for multiplication, while in 2D we use y:=a·b; Maple will replace the * by a middle dot automatically when in 2D mode. In 1D mode, we would differentiate 3x2 + 2x with y:=diff(3x2 + d 2x,x): in 2D mode we would have y: = (3x 2 + 2x ). dx

1.2 The Maple interface When a Maple 2017 session is initiated, the interface appears as in figure 1.1 with the Start.mw document open. At the top we have the menu bar; many of the tabs (for example, File) will be familiar to a Windows user. Below that we have a toolbar. The first five of these will be familiar: open a new document, open the folder used to store one’s Maple files, the floppy disk icon which may be used to save one’s work, the print and print preview tools. To the left we have the Maple pallets. Currently only the Expression palette is expanded while the rest remain closed, but with the Start.mw worksheet active, the palettes are grayed out. The purpose of Context Bar with the tab tools (Text, Math, Drawing, Plot and Animation) will be explained as we proceed. The major part of the interface is taken up by the work area. Many of these icons lead the user to various tutorials and example files. The reader is encouraged to doi:10.1088/2053-2571/ab0bb3ch1

1-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 1.1. The Maple interface.

Figure 1.2. Open files in the tab area.

explore! For now, we will concentrate on two of the icons just above the word Start in the white space. We have the choice of opening a new file in either document or worksheet mode. The differences are mainly one of appearance, as will become clear as we proceed. For this introduction, we will choose to open a new document. A new document mode file can also be opened by clicking the first icon in the toolbar or by using the shortcut CTRL+N—a common shortcut in many Windows applications. In figure 1.2 the user has opened a new document, clicked the Text tool (the uppercase T in the toolbar, or clicked the icon tool Text and set the box below it to C Text) and typed a few words—see figure 1.3. Note that above Text, Math, Drawing, etc, we see the name of two files. The user has just made a file and since it has not been saved it has the name Untitled. The asterisk to the left of the name warns the

1-2

Maple

Figure 1.3. Simple input–output.

user that the file has been changed but not saved. The X to the right may be used to close the document; if it is unsaved Maple will ask if you wish to save it. The name and saved status of the currently viewed document also appears in the Maple windows title bar. We will not investigate the meaning of [Server 3] in the title bar. Below Text, Math, Drawing, etc, we have a box currently reading C Text followed by tools to format the selected text.

1.3 Entering simple expressions [SimpleA.mw] Figure 1.3 shows some simple inputs and outputs. The first two statements cause Maple to do simple calculations. Next, numeric values are assigned to two names (a and b); this is how Maple refers to a string of characters used to hold data. The reader should not get excited by this; 1-3

Maple

they are just variables with another name. The most important feature is the use of a colon followed by equals (:=) in the assignments. Note the colon following the definition of a, and the absence of any symbol after the definition of b. We could have used a semi-colon at the end as in a:=3+7; b:=4; The semi-colon causes Maple to output a result. This output is centered in the workspace and uses a blue font. Each statement that generates output gets a number displayed in bold; Maple refers to these as labels. The variable c is then assigned to the quotient of b and a. When working with integer values (and with the constant π), Maple normally generates output in rational or exact form as in outputs (2) and (5). The evalf command is used to cause Maple to generate a decimal (floating-point) value—see output (6). There is more on evalf later in the chapter. Be careful to note the final f in the command name as eval is something different. The statement c·1.0 (i.e. multiplying the variable by a floating-point number) would yield the same result. Following this, we assign values to variables k and m; because the statements end with colons no output is generated. These are used to define the variable j. To enter m2 one types m^2 and Maple converts this to 2D mathematics with the cursor flashing next to the superscript and the user must tap the right arrow key to return to the baseline. Note that because at least one of the variables is non-integer, the output is a floating-point number. The definition of v also yields a decimal value since k is a floating-point value. The statement evalf[3](v) results in displaying v with 3 significant figures (not 3 decimal places). In the final statement (10) the original output was the same as in (8), but by right-clicking the output and calling up the Numeric Formatting dialog (figure 1.4) we have caused it to be displayed with 4 decimal places. [SimpleB.mw] Figure 1.5 shows some further examples. To make a neater screenshot, we have used CTRL + = to generate in-line output; do not type the = symbol as Maple will generate it when CTRL + = is used. The output from the

Figure 1.4. Numeric formatting dialog.

1-4

Maple

Figure 1.5. Further examples of rational output.

definition of variable a is rather complex. The simplify command improves it somewhat. The surd1 function surd(x, n) returns the nth root of x. We first find c as (−27/64)1/3; then we square that result. Next c is evaluated as a floating-point value. The last statement shows an example of the convert command. The reader is encouraged to open a new document in document mode with CTRL +N and add the execution blocks as shown in figure 1.3. Begin by clicking on Text or the T in the toolbar, and entering the text shown at the top of the figure. Hit the Enter key and click on Math. Here are some pointers. (a) Maple is case-sensitive; the names amp and Amp refer to different variables. Some words (exp, root, max) are reserved and may not be used as names; Maple will warn you if you err in this regard. Capital D is reserved so it may not be used as a name. Capital I is used by Maple for √–1; a value normally represented by lowercase i or j. (b) If you have assigned a value to a name, for example x := 3, and later wish to use that variable for another purpose you can nullify the assignment with a statement in the form x := ‘x’ with the variable name within simple quotes on the righthand side. (c) Maple expressions can end with either a semi-colon (;) or a colon (:). The final semi-colon is optional. Use a colon when no output is needed. In document mode, terminating an expression with CTRL+ = gives output on the same line as the input. In worksheet mode, it has the same effect as a simple Enter. In worksheet mode, use SHIFT+ENTER to continue a statement in the line below. (d) To insert a multiplication sign, use the asterisk. If you type x:=a*b, Maple will change the * to a mid-dot as in x:=a·b. However, the output will be x:=a b with a space to indicate implied multiplication. The user could input the expression with a space, but this can lead to problems if one 1 Maple commands are displayed on the Maple workspace in italic but surd is a Maple function so it is not italicized on the workspace.

1-5

Maple

(e)

(f) (g) (h)

(i)

(j)

(k) (l) (m) (n) (o)

mistypes. There is no need for the multiplication symbol when using a number: for example both b := 3·a. and b := 3a are acceptable. For division use the / key. Statement 5 is entered as c := b/c. The definition of v in output (8) began as v := m/m + k, then the right arrow key was pressed before typing the multiplication symbol * followed by 5. To enter, for example x2/3, type x^2/3 followed by the → keyboard key. The last statement (v #formatted to 4 decimal places) shows the use of the # symbol to insert an in-line comment. Whenever you find it necessary to edit a statement it is advisable to have Maple update the calculations. Do this by clicking the icon with three !!! to recalculate the entire document or the icon with one ! to recalculate the selected statement. When working in document mode use CTRL+SHIFT+K to insert a new paragraph (a new line) before the cursor, and CTRL+SHIFT+J for insertion after the cursor. In worksheet mode CTRL+K inserts a new execution block before the cursor, and CTRL+J does this after the cursor. In document mode, a line may be removed using the Delete or Backspace keys; to remove an execution block use CTRL+ALT+SHIFT+E to select it, then use the Delete key. A statement may reference the labeled output above it. For example, both evalf(%) and evalf((5)) would give the same output as evalf(c) in figure 1.3. The symbol % references the previous output while %% references the one above that. One cannot just type the output label; type evalf(, then use the command Insert ∣ Label .. (or the shortcut CTRL+L) to call up the dialog shown in figure 1.6. Note: older book and webpages use the double quote (“) rather than % but newer versions of Maple will not understand evalf("). Function arguments are always delineated with parentheses, i.e. (…). Sets are always delineated with curly brackets, i.e. {..}. Lists are always delineated with square brackets, i.e. [..]. Variable ranges (for integration, plotting, and counting) look like this: x = 0…2, which would mean that 0⩽ x⩽ 2. A question mark? followed by a Maple command name will elicit more information on that command, as well as detailed examples.

Figure 1.6. Insert label dialog.

1-6

Maple

d (3x 2 + 2x ) the user has two options. In dx figure 1.7, the user to the left has typed y:= and then selected the differential object from the palette. The x and the f (shown in different colors) are called placeholders; the user moves from one to the other with the TAB key. On the right, the user has typed diff and then hit the ESC key (called the Expression Completion key in Maple) to bring up a dialog from which the required object may be selected. The user would then fill in the placeholders as before. Alternatively, the user could just type y := diff(3x2 + 2x, x) and leave the input in 1D mathematics.

(p) To enter a statement such as y: =

1.4 The use of evalf[d](term) [EvalProb.mw] The use of a statement like evalf[3](c) (or its equivalent, evalf (c,3), which is the older syntax) for formatting purposes, is risky. Never use such an expression before the first time that variable c is computed. This is demonstrated in figure 1.8. The document was prepared in Worksheet mode (hence the angled prompts >) but that need not concern us here. The variables x and y have identical definitions. Variable ans (equal to y) is computed in output (4) and displayed with 2 significant figures as 0.0034 in (5). No problem here, but it is important to note that the [2] does not result in 2 decimal places but 2 significant figures. In (6), the value of x is found with evalf[2](x) giving 0.0035. One might have expected the same value as ans. The statement in (6) does not first compute the expression and then display the answer using 2 significant figures. Rather it rounds each term in x to 2 digits and then does the computation; this is demonstrated in statement (7). Moral: If you perform the calculation before using the evalf[d](expression) all will be OK. The author generally prefers formatting to using evalf with a d value. However, he wonders about the ‘naked’ decimal point (the leading zero is absent) in output (8)— the author’s boyhood math teacher found such things an abomination!

Figure 1.7. Two ways to enter the differential object.

1-7

Maple

Figure 1.8. The danger of the evalf[d](expression).

1.5 Some handy algebraic commands [Algebra.mw] Figure 1.9 shows the use of the commands simplify, normal, expand, factor, and coeff. These commands can be used to assign values to variables. For example, we may use co3:=coeff(%,x3). The operations of expand and factor are fairly obvious. To quote from Maple Help: ‘The simplify routine searches the expression for function calls, square roots, radicals, and powers, and invokes the appropriate simplification procedures.’ The command normal generally gives an answer in the form numerator/denominator. As can be seen, the two often produce the same result. The command coeff (p, xn) extracts the coefficient of x^n in the polynomial p; an alternative syntax is coeff (p, x, n). The command convert(f, parfrac, x) performs a partial fraction decomposition of the rational function f in the variable x. The third parameter can be omitted when f contains just one name. Look at the commands involving Z. The factor command does not help, but when we give it a field extension of sqrt(3) the result is more informative. Likewise, for the Q examples, simplify seems useless until we add a second parameter. [Trig.mw] Figure 1.10 shows some uses of these commands with trigonometric functions. The examples in the two figures are mainly to show the reader what is possible; a detailed explanation would be inappropriate here, but the Maple help facility will explain all. Maple expects angles in radians.

1-8

Maple

Figure 1.9. Same algebraic commands.

1-9

Maple

Figure 1.10. Expand and simplify with trig commands.

Figure 1.11. Context menus.

1.6 Context menus [Contex.mw] When working in document mode, if an item is right-clicked a context menu appears. This allows the user to perform many operations without knowing the details of Maple’s commands. Figure 1.11 shows a few examples. The user typed the expression 3x + 5=5x - 3, and, without using the Enter key, they right-clicked the expression bringing up the context menu shown in figure 1.12. Within that menu they clicked Solve followed by Isolate for x. We may summarize this as Right-click | Solve | Isolate for| x.

1-10

Maple

Figure 1.12. Using Solve.

In the second example the sequence was Right-click | Solve | Obtain Solution | x. The sequence Right-click | Plots | 2D Plot was used to generate the plot; chapter 2 contains more information on plotting. Factorization was obtained with Right-click | Factor. The final example shows how one may use context menu operations on the outputs of previous operations. The reader is encouraged to experiment with context menus. Maplesoft uses the term Clickable Math for this type of work. This text uses the feature sparingly as it is best documented by videos. The reader might wish to explore the topic at these sites: https://maplesoft.com/products/maple/demo/player/ClickableMath.aspx and https:// www.maplesoft.com/products/maple/academic/applications.aspx. [WorksheetContext.mw] When the user right-clicks an expression in worksheet mode the same context menu appears but the results are different. To explain what is happening, comments have been added to figure 1.13. There are a few things to note:

1-11

Maple

Figure 1.13. Results from the Context menu in worksheet mode.

(1) The author has found that when an assignment ends with a colon (as in y:=2x2 - 3x +5:) the context menu is limited. When output is allowed, the menu is as in figure 1.12. For this reason, all statements in figure 1.13 have output. He has not found any documentation on this. (2) This method can be useful in learning Maple. For example, when Prime Factors selected the k := 102/979, Maple automatically loaded the PrimeFactors module from the NumberTheory package. So the user now knows how to find factors without the context menu.

1.7 Formatted output with printf [Printf.mw] It is sometimes helpful to generate formatted output. Figure 1.14 shows a simple example. Before we examine the syntax of printf let’s look at the last command in the figure. We have asked for the formatted output of the variables a, b, and c; but c is undefined. That triggered the error message. One of the few bugs in Maple is that this references fprintf and not printf. Also, note that for variable a no decimal place value was specified so the output has 9 significant figures. The syntax for printf is printf(fmt, x1, ..., xn) where fmt is a string listing the format specifications; the user may include text within the string, and x1, x2 … is a list of variables. The format specifications are shown below in table 1.1. Each begins with the % symbol; W is the character width and D is the number of decimal places, the final symbol (d, f, or e) denotes integer, floating-point, and scientific. A user familiar with the C language will recognize this syntax.

1-12

Maple

Figure 1.14. Example of printf.

Table 1.1. Format specifications for the printf command.

Type

Format

Example

Integer Floating-point Scientific

%Wd %W.Df %W.De

%5d will print a signed integer up to 5 digits in length %5.6f %19.12e (choose W ⩾ D + 7)

In the second printf, we have used W with a value of 6; the output shows spaces before the first digit. To generate a new line after the output, use /n within the fmt string—see the output from the second printf.

1.8 Data structures [SeqSetList.mw] In addition to vectors and matrices, which we discuss in a later chapter, Maple offers four ways of grouping numeric data: sequences, sets, lists, and arrays. Each has its own use; for example, set-theoretic operations like union are possible with sets. Figure 1.15 shows some simple examples of defining the first three. Before commenting on the document, let us see how you can compose a document like this. Open a new document; the cursor will be flashing and in italic, indicating math mode. Press F5 to switch to text mode. Type the first line and tap the Enter key. Type Example of a sequence and add some spaces, tap F5 and 1-13

Maple

Figure 1.15. Sequence, set, and list.

type a:= 2, 4, 6, 3, 2, followed by CTRL+= to give output on the same line as the input—the feature works only in document mode. Tap the Enter and F5 keys and start the next line. While each definition has a series of numbers separated by commas, the sequence is not enclosed. The set is enclosed by curly braces { } and the list by square braces [ ]. A notable feature is the set ends up being sorted with duplicates removed. The figure also shows examples of functions and commands; some do not work with sequences. [SeqSetList2.mw] Figure 1.16 shows further operations on sequences and lists. Having defined list L and sequence S, the worksheet shows how to execute elementwise operations using a tilde (∼) after the mathematical operator; for example, the fourth statement reads Q:=L*~2, to multiply each element in L by 2. The add and mul commands find the sum and product, respectively, of specified elements in a sequence or list. Compare this with the sum command2 that internally generates a sequence and performs the addition.

2

The command Sum (with capital S) is termed an inert command; these are generally used for documentation.

1-14

Maple

Figure 1.16. Some operations on lists and sequences.

The convert command may be used to convert one structure to another; an example of this is shown in figure 1.17. The elements of a list can themselves be lists. As an example, consider L := [ [1,3], [2,5], [3,7] ], this could be a list of points (the x, y coordinates) of a line. Maple describes lists as being immutable. An element in a short list can be changed, for example L[2]:=√2, but this can cause errors with a long list. Even changing an element in a short list requires Maple to generate a replacement list so there is a time penalty. A new list must be made if one wishes to extend a list: suppose L is [5, 6, 7] then the statement L2:=[3,op(L)] will generate the list L2 with elements [3, 5, 6, 7]. A one-dimensional array is in many ways similar to a vector and a twodimensional array is similar to a matrix. However, an array may have up to 63 dimensions! Also, the definition a:=Array(0..4) makes an array with indices 0, 1, 2, 3, and 4. Vector and matrix indices always begin with 1. [Array1.mw] In this worksheet (figure 1.17) the array a is made using the Array constructor3; the array elements are then given values. Output (3) shows the construction of array b giving its elements values at the same time. Output (4) shows how one may access a given element. The use of the fill option is shown in output (5). Output (6) demonstrates the commands ArrayNumDims and ArrayNumElems. In the last execution block in the figure, a list is defined and converted to an array.

3

Be careful to use a capital A so as to avoid using the deprecated array constructor.

1-15

Maple

Figure 1.17. Construction arrays.

Figure 1.18. An array with two names.

[Array2.mw] Figure 1.18 shows a rather odd behavior of arrays. The statement b:=a does not make a new array; rather it makes b a synonym for a. Each variable references the same object so changing an element in b is the same as changing it in a. [Array3.mw] The starting index for an array dimension does not have to be 1. Figure 1.19 shows a one-dimensional array with indices −1, 0, 1. The array does not display as neatly as before but that is the only difference.

1-16

Maple

Figure 1.19. Experiment with indices.

Figure 1.20. Defining functions.

Arrays are special types of Maple tables; this topic is beyond the scope of this book—use ?tables in a worksheet to learn more.

1.9 Defining a function [Function.mw] As a means of demonstrating the difference between a named expression and a function, figure 1.20 begins with the variable g being assigned an expression in x and then we see how one can evaluate the expression for some value of x. Then f is defined as a function of x; and evaluated for a specific x value. Finally, we define r as a function of the variables x and y. Things to note: (1) The expression g is evaluated with eval not evalf. (2) Input (3) shows the → method to define a function. The symbol → (the functional operator) is made by typing — followed by >; Maple makes the conversion. When there is more than one variable in the definition, they are 1-17

Maple

grouped in parentheses. To define r with the arrow method one would use r:= (x, y)→sqrt(x2 + y2). The Expression palette may be used for this method. (3) Input (5) shows an alternative method to define a function.

1.10 Debugging a worksheet You have entered a fairly simple statement, but the result is rubbish; what went wrong? Some possible answers: (i) You think a name has been defined but when you try to use it, it results in nonsense. Perhaps you entered a=x2+3, when what was needed was a:=x2+3. This will be a very common error while you are learning Maple. Conversely, within a command you needed to use something like x=0, but you mistakenly entered x:=0. (ii) You have typed two variables (e.g. mg) when you needed to enter two variables with a multiplication (e.g. m*g which displays as m·g). Do not use the implied multiplication trick of leaving a space between the m and the g; this can lead to chaos! (iii) You typed a command such as blah(eq) and the result was blah(eq) when you expected a meaningful result. Possible reasons are: (a) misspelling —you wanted to find the cosh−1 of an expression but entered arcosh(eq) when arccosh(eq) was needed, (b) wrong capitalization of first letter— most common commands use a lowercase, many commands in a package use uppercase, but there are commands like Diff and diff where the uppercase one is an inert command, or (c) you referenced a command but did not load the required package4—example display needed the with(plots). (iv) You have edited a statement and not recalculated the worksheet with the icon !!!. (v) Every left bracket (e.g. (, [, {, ). Maple will throw a cannot parse error if you fail in this regard. (vi) Oh yes, did you remember to start the worksheet with restart? There are few cases when this is not required, If all else fails, you can contact the Maple community at https://www.mapleprimes.com/ where questions can be posted. The site makes it easy to display the content of a worksheet, making it easier to describe your problem and to upload a sample file so that community members can quickly work out a solution for you. Generally, the person replying will post back an edited file. Save your work frequently and limit the number of open workbooks. The author has experienced several occasions when Maple froze and only Task Manger would close it; meaning all unsaved work was lost.

4

If you use restart after a with(package) command, the package will be unloaded.

1-18

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 2 Introductory examples

This chapter shows some examples of the use of Maple; the problems are kept very simple to avoid the need for lengthy explanations. The focus here is on Maple features. Most of the files are in worksheet mode; note that each document (regardless of mode) begins with the restart command.

2.1 Ammonia [Ammonia.mw] We start with a very simple problem: find the pressure of one mole of ammonia at 273 K in a volume of 22.4 l using the ideal gas law and the van der Waals equation; find the critical temperature of ammonia (figure 2.1). The only comment needed is to point out that in p[ideal], p[vdw] etc, the bracketed items (e.g. [ideal]) are label subscripts as seen in the output.

2.2 Water pump [PumpWater.mw] Water is pumped at a rate of 0.25 m3 s−1 from a well that is 25 m deep. At the pump output, the water has a velocity of 8.5 m s−1. If the efficiency of the electric pump is 80%, how much power does it draw? For a change of pace this problem is solved using document mode—figure 2.2. We are working in SI units, so we need to multiple the density (1 gm cm−3) by 1000. The units of W are kg m2 s−2; dividing this by 1 s (no need to show this in the unitless worksheet!) gives power in units of kg m2 s−3 and this is equivalent to watts. In chapter 5 we redo the problem using Maple’s units thus relieving the user of having to know this fact.

2.3 Telescope resolution Telescope problem [Telescope.mw]: A telescope is used to observe, at a distance of 10 km, two objects which are 12 cm apart and illuminated by light of wavelength 600 nm. Estimate the diameter of the objective lens of the telescope if it can just resolve the two objects. doi:10.1088/2053-2571/ab0bb3ch2

2-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 2.1. Ammonia pressure.

Figure 2.2. Pump problem.

The relevant formula for this is Rayleigh’s criterion: two point objects making an angular resolution of θ are distinguishable if the diameter D of the telescope satisfies D > = 1.22λ/θ provided D ≫ λ, which will be true for telescopes. We use the geometric approximation θ = s/z where z is the distance from the object to the objective lens and s is the separation of the two objects and z ≫ s. Before assigning value to the variables, care should be taken to convert to consistent units. The problem above is solved in figure 2.3 which computes the diameter as 6.1 cm. We use

2-2

Maple

Figure 2.3. Telescope resolution.

Diam rather than just D since that is a reserved symbol in Maple. In a later chapter we add units to the variables (e.g. z:= 10km) and let Maple do the unit conversion.

2.4 Velocity of a bullet [Bullet.mw]: A gun fires a bullet of mass m at a block of wood of mass M; the block with the embedded bullet travels a distance s on a surface with a kinetic coefficient of friction μ. We wish to find the velocity of the bullet vb on impact given: m = 10 g, M = 4 kg, s = 15 cm and μ = 0.4. In figure 2.4, we use the conservation of momentum for an expression of vb (vB is the velocity of the block plus bullet just after impact); the expression for vb comes from the third equation of motion (relating velocity and distance), and the expression for acceleration a comes from the definitions of force and μ. When we ask Maple to display vb —output (1)—we see that Maple has made some useful substitutions, and when we assign values to all variables (being careful to get everything in consistent SI units1), the numeric is returned with the awkward √2 term. The command evalf(vb) would have given 434.858 57. The round function returns the velocity rounded to the nearest integer. The reader may wish to experiment replacing the integer 2 in the first expression by the floating-point value 2.0, and another experiment to show that the expression can be in any order.

2.5 Solve puzzle [SolvePuzzleAlgebra.mw] Here is a puzzle taken from a newspaper—figure 2.5. We use Maple to perform the operation that one might do in a pen-and-paper solution. 1

In anticipation of chapter 5 the bullet problem is solved with units in [BulletUnit.mw].

2-3

Maple

Figure 2.4. Velocity of a bullet.

We enter two expressions using the data given in the puzzle. The solve command is covered in detail later; here it is used essentially to change the first expression to C = A - 8. The eval command replaces the C in the second expression by A - 8. Note this is eval without a final f. We could have used the subs command—the reader may wish to enter the statement ?subs into a worksheet to learn more. The result is a bit messy, so we use simplify. Multiplying the result by 4 gives a nice quadratic so we factorize this as a simple way of solving it (an operation we could have done mentally!). Surprisingly, if we write the expressions AveKids := (A+C)*(1/2)=4; and AveSibs := (A*(A-1)+C*(C-1))/(A+C)=4; the worksheet is far less successful.

2.6 Vertex form In many pre-calculus courses, students are required to convert a quadratic expression from the standard form y = ax2 + bx + c to the vertex form y = a(x − h)2 + k using the method of completing the square. The steps may be summarized as: (i) move the c term to the left, (ii) factor out the coefficient of x2, (iii) add the square (b/a) to the second term in step (ii) and subtract it from the constant on the righthand side of the equation, (iv) form the square and return the constant from the left to the right. If the reader needs a refresher in this please see: https://mathbitsnotebook.com/Algebra1/Quadratics/ QDVertexForm.html or https://www.purplemath.com/modules/sqrvertx.htm. [Vertex.mw] Figure 2.6 shows the screenshot of a document mode worksheet, where we have chosen to mix text and formulas on one line and to use CTRL+= to get 2-4

Maple

Figure 2.5. Solve a puzzle.

the output on the same line. The second statement is rather unconventional; it is equivalent to a:=2; b:=-4; c:=5. By using the format shown, we have just one place to change when experimenting with other quadratics. The other statements are straightforward. The reader should experiment with f = 3x2 + 2x − 1 to show the vertex is at (−1/3, −4/3). In a later chapter we will see a plot that allows the user to observe the result of altering h and k. In another chapter, calculus is used to show that h = −b/2a and k = f(h). [CompleteSq.mw] After all that work, we take an excursion: we experiment once again with the context menu. The worksheet in figure 2.7 begins with a quadratic expression; when this is right-clicked, the user selects Complete Square / x to get the result shown. Maple has anticipated the needs of students to perform this complete-the-square task. So far this worksheet is OK but it is static; changing the expression does not give a new result since the expression was ‘hard-coded’ into Student[Precalculus][CompleteSquare](x^2-4*x+7, [x]). A bit of experimentation shows us that the statement Student[Precalculus] [CompleteSquare](f) can be used dynamically.

2-5

Maple

Figure 2.6. Vertex form of a quadratic.

Figure 2.7. Complete the square from the context menu.

2-6

Maple

2.7 Classic inclined plane problem [InclinedPlane.mw] This worksheet (figure 2.8) should be self-explanatory. All numeric values are in standard SI units (kilogram, meter, second). A space was made for the picture using the Enter key and the picture was copied and pasted from another application.

Figure 2.8. Inclined plane problem.

2-7

Maple

2.8 Baseball problem [Baseball.mw] Figure 2.9 shows a classic kinetics problem and its solution. Parts (a) and (b) get solved in a very direct manner—simple substitution of numbers for 0 2 − vo 2

variables. When coding d: = −2·g begin with d : =02 − vo2 , use the mouse to select all of the righthand side, and then type the / to start division. Part (c) results in a quadratic equation that we solve by factorization; the required values are evident when we look at output (5). In case these values are needed for further work, they are extracted individually. Note the use of the op command to extract an operand from an expression. In statements (6) and (7) we first extract and then solve; in statement (8), the two operations are combined. The solve command just finds what value of the variable tt makes the righthand side of the expression

Figure 2.9. Baseball problem.

2-8

Maple

equal zero. In chapter 4 we will see the use of solve to directly solve the quadratic name here eq.

2.9 Center of mass Our task here is to compute the center of mass (centroid) of a plate of uniform thickness having the shape shown2 in figure 2.10. For a polygon having N sides (and N vertices), the centroid can be computed using these formulas: N −1

A=

1 ∑ (xiyi+1 − xi+1yi ) 2 i=1

Cx =

1 ∑ (xi + xi+1)(xiyi+1 − xi+1yi ) 6A i = 1

Cy =

1 ∑ (y + yi+1)(xiyi+1 − xi+1yi ) 6A i = 1 i

N −1

N −1

These equations are applicable for non-self-intersecting polygons (no line in the polygon’s drawing crosses another); this is not a serious constraint, as we are interested in polygons that can be made into physical objects.

Figure 2.10. Regular laminar plate.

2 This diagram is an exported plot generated in the file COMListPlot.mw with third-part software being used to add notations.

2-9

Maple

Figure 2.11. Centroid of a polygon.

[Centroid1.mw] The worksheet is illustrated by figure 2.11. The vertices are recoded in two Maple lists; one for the x-values, one for the y-values. In the expression for A, using 1.0 as the numerator rather than a simple 1 ensures the results will be displayed as floating-point numbers without the need for the evalf command. The expressions for Cx and Cy are in a single execution block; this gives a tidy output with the two values in one area. To get this effect once the Cx expression has been entered, use SHIFT+ENTER to start a new line within the same execution block, and then enter the second expression. Note that the first expression must terminate with a semi-colon. When developing a new worksheet, it is always a good idea to get an independent check on the results. In this case an Internet search reveals several polygon centroid calculators; for example https://www.easycalculation.com/area/polygon-centroidpoint.php. It is instructive to extend this task to make a more general worksheet that can be used for any three-part polygon, and we will allow the parts to have different densities. [Centroid2.mw] The worksheet (figure 2.12) is very similar to the first one, but it has data and calculations for three polygons (three rectangles). Output is suppressed in the figure but initially it is a good idea to view each result and compare them with the expected results. Each part is treated as a particle of mass mi located at (Cxi, Cyi) to find the overall centroid using: n

n

∑mi Cxi CentX =

i=1

M

∑mi Cyi and CentY =

2-10

i=1

M

n

where M =

∑m1 i=1

Maple

Figure 2.12. A more general computation of the centroid.

2-11

Maple

Figure 2.13. Calibration of a trough.

While we have made provision for allowing each part to have its own density (note we need only relative densities) we have initially set each to unity. The multiplier 1.0 in the expression for M is used to ensure we get floating-point outputs for the centroid coordinates. To get a neat final output this time, the two expressions are entered in one line. 2-12

Maple

A note on repetitive expressions: One way to enter these formulas is by copying and editing. If one enters the expression for A1, and uses a copy and paste operation, one can then change all subscript 1s to 2s to get A2. Likewise, copy Cx1, change (X[1][i]+X[1][i+1]) to (Y[1][i]+Y[1][I+1]) to get Cy1. In chapter 9 we avoid this complication by using loops for the various calculations.

2.10 Trough problem [Trough.mw] A trough3 of length L has a semicircular cross section with radius r. When filled with water to within a distance h of the rim, the volume V is given by

⎡ ⎤ ⎛h⎞ V = L⎢0.5πr 2 − r 2arcsin⎜ ⎟ − h(r 2 − h 2 )½ ⎥ ⎝r⎠ ⎣ ⎦ Our task is to provide a calibration such that a user who knows the value of h can find the volume of water in the trough. The data is in feet, so V is found in cubic feet. In figure 2.13 we begin in a tentative way; knowing that typing a long formula is prone to typo errors, we enter expressions for each term in the formula for V. We can double check the results of each with a handheld calculator. Emboldened by success, we adopt a function approach. If the user changes h:=5/12 to some other value, a new volume will result. Anticipating the next chapter, a plot of the function is generated. Note how we used words like radius and height, but truncated length to len. Maple will complain if you try to use length as a name because it is a reserved word.

3

Faires J D and Burden R 1998 Numerical Methods (Pacific Grove, CA: Brooks/Cole) p 41.

2-13

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 3 Plotting with Maple

3.1 Starting with plot In this chapter we take a quick tour of Maple’s plotting features. For more details visit https://www.maplesoft.com/support/help/Maple/view.aspx?path=worksheet% 2freference%2fPlottingGuide. [Plot1.mw] Figure 3.1 shows three simple plots from which we learn the following: (a) The default x-range of a plot is generally −10 to +10 but when a trigonometric function is involved it is −2π to +2π. (b) The second plot shows that the x-range may be set using the second parameter as in x = –5…5. (c) To plot multiple functions, we use a list as the first parameter as in [f, 30 sin(x)]. (d) With multiple plots the first function is displayed in blue and the second in red. A third function would be shown in green. These colors can be overridden as in plot([a,b,c], color=[red, blue, black]). (e) When a plot is clicked, it is displayed with a border having resize handles. All the charts in the figures made been made a little smaller than their original size. Unfortunately, dragging a corner handle does not simultaneously resize both the vertical and horizontal size; this would preserve the aspect ratio. Also, when a plot is resized, the font for the axes labels is not altered; this requires an additional effort by the user—see labelfont in figure 3.4. A plot can be given a set size with the size = [w, h] parameter within the plot command. An example is shown in figure 3.5; for more details enter the command ?plot/size in a worksheet.

3.2 Plot tools A plot may be customized in several ways: using the Plot clickable tool, using the context sensitive menu which is displayed when one right-clicks a plot, or adding parameters to the plot command. doi:10.1088/2053-2571/ab0bb3ch3

3-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 3.1. Some simple plots.

The Plot tool (figure 3.2) has a limited number of features. From left to right: (1) Line or markers (note the drop down); (2) Position of axes (note the drop down); (3) Makes the scale of the two axes the same; (4) Point probe; (5) Selection tool; (6) Execute code; (7) Pan; (8) Zoom in; (9) Zoom out;

3-2

Maple

Figure 3.2. The Plot tool.

(10) Reset view—a lifesaver if you experiment with the other tools; (11) Axes properties; opens the axes dialog (note the vertical and horizontal tabs); (12) Toggle the gridlines; (13) Gridline properties: opens the gridline dialog. The interested reader should experiment to gain more insight into these features.

3.3 Customizing with the context menu Figure 3.3 shows a plot before and after customization. To the right is the context menu. The Titles feature was used to get a title on the lower plot. Using Axes ∣ Labels ∣ Add Horizontal and Add Vertical, axes labels were added. The legend feature was used to edit the legend1. The pair of superscript 2s in the legend were made with ALT + 0178; the digits being from the numeric keypad.

1

3-3

Maple

Figure 3.3. Starting the customization.

When the point probe is over a specific object (in the figure it is over one of the curves) the context menu relates to that object, otherwise it relates to the whole plot. The Export feature allows the user to save an image (in various formats) of the plot.

Important note: Any customization done with the context menu will be lost if the worksheet has a restart statement and it is recalculated.

3.4 Customizing a plot with parameters In the above section we customized a plot using a context menu; a plot may also be customized with parameters. Of course, one may combine these two methods. It is left to the reader to find out what happens if you give two conflicting commands such as specifying a curve color as red in a parameter and blue in the context menu! For more information on plotting: (a) Common options: https://www.maplesoft.com/support/help/Maple/view. aspx?path=plot%2fdetails or use the command ?plot/details, (b) All options: https://www.maplesoft.com/support/help/Maple/view.aspx? path=plot/options or use the command ?plot/options,

3-4

Maple

Figure 3.4. Logarithmic plot.

(c) Customizing axes: https://www.maplesoft.com/support/help/Maple/view. aspx?path=plot/axis or use the command ?plot/axes, (d) Information on color: https://www.maplesoft.com/support/help/Maple/ view.aspx?path=plot/color or use the command ?plot/color. Here are some examples of parameters: axesfont = ["HELVETICA", "ARIAL", 8] color = [steelblue, black] labeldirections = ["horizontal", "vertical"] labelfont = ["HELVETICA", 10] labels = ["x values", "y values"] legend = ["Sine Plot", "Cosine Plot"] legendstyle=[font=["HELVETICA",9], location=right] linestyle = [solid, longdash]

3-5

Maple

Figure 3.5. The logplot command.

title = "Simple Trig Functions" titlefont = ["ROMAN", 15] When a list relates to the axes, as in labeldirections = ["horizontal", "vertical"], the first value is for the x-axis, the second for the y-axis. When the list refers to plotted expressions, the order is the same as that of the expression list— as in the color2 example above.

2 Maple very obligingly allows for standard (e.g. colour) and US (e.g. color) spellings; one can even use both in the same statement.

3-6

Maple

3.5 A logarithmic plot [LogPlot1.mw] Figure 3.4 shows plots of exp(x2); one with a linear vertical axis and the other with a logarithmic vertical axis. To achieve this, right-click the plot (with the cursor not on the curve), from the context menu select Axes and then select Properties. Open the Vertical tab as shown to the right in the figure, and check the Log mode box, click the Apply and OK buttons. [LogPlot2.mw] Figure 3.5 gives an example of the use of the logplot command, which requires the plots package. Using either method, when the y range is several decades, the y-axis will display values such as 102, 103, etc. To achieve a logarithmic scale on the x-axis: (a) open the axes properties and move to the Horizontal tab, or (b) use the semilogplot.

3.6 Using display for multifunction plots [DisplayPlot.mw] Figure 3.6 shows an alternative way of generating a multifunction with the display command. This is useful when you need to specify various features for each function. Note the display command requires the plots (the final s is essential!) package to be loaded.

Figure 3.6. Using the display command.

3-7

Maple

We have jumped ahead a little and used the diff command to differentiate an expression; more on that in a later chapter.

3.7 Two plots side by side [SideBySide.mw] This worksheet (figure 3.7) illustrates how to plot two functions side by side using an array and by using a comma between the plot commands. In the first method: the two functions are entered and a two-by-one array named A is constructed. Into the array are placed not text, or numbers, but objects—plots. The statement tells Maple to show A and this generates the side-by-side diagram. In the second method we use plot(f…..),plot(g….) with a comma between them;

Figure 3.7. Side-by-side plots.

3-8

Maple

Figure 3.8. Seq used for a family of curves.

unfortunately the comma gets displayed with the plots. With either method it is cumbersome to alter the size of the plots by dragging.

3.8 Plotting a family of curves [SeqPlot.mw] Figure 3.8 shows the use of seq within the plot command to generate a plot of a family of curves.

3.9 Plotting digitalized data [DataPlot.mw] Figure 3.9 shows several ways of plotting digitalized data. The first way plots points together with a curve. The points are entered as a list, each point is itself expressed as a list; the element [−5, 0] represents the Cartesian coordinated (−5, 0). The second way plots data stored in two vectors, one for the x-values, and one for the y-values. Here we plot just the digital data. The third plots the digital data as joined points together with the curve.

3.10 Parametric plots [Parametric.mw] A point on a unit circle is represented in Cartesian coordinates by (x, y) such that x 2 + y 2 = 1. We may also state the coordinates of a point as (cos(t), sin(t)) since cos2(t ) + sin2(t ) = 1 for all values of t. In this form, t is called the parameter.

3-9

Maple

Figure 3.9. Plotting points.

3-10

Maple

The Maple syntax for a parametric plot is plot([x(t), y(t), t = range of t], h, v, options); where x(t) is the parametric function for the x-values, y(t) for the y-values, h the horizontal range, and v the vertical range. Figure 3.10 demonstrates three such plots.

Figure 3.10. Parametric plots.

3-11

Maple

3.11 Using the coords = polar option This option is a little difficult to get one’s head around. Hopefully these examples will help. There is an excellent explanation at http://ostts.org/Stitz_Zeager_ Precalculus_Book_By_Section_files/11-5.pdf. [PolarCoordsA.mw] If we make a plot of x = 4, we get a horizontal line passing through y = 4 because for all x-values the function has a constant value of 4. But if we add the option coords = polar to the plot command we get a circle because the points that remain at a distance of 4 from the origin for all θ values have a locus of a circle. To convert from Cartesian to polar we use the equations

Figure 3.11. Explaining the coords = polar option.

3-12

Maple

x − > r · cos(θ ); y − > r · sin(θ ) with r = x 2 + y 2 . So our y = 4 generates a circle of radius 4. This is shown in the left part of figure 3.9. [PolarCoordsB.mw] The righthand part of figure 3.11 is a further example. A plot of 2 + 2cos(θ) generates a limaçon (also called a rose curve). The top plot is using the option coords = polar—the plot is in the xy plane, the lower plot is a true polar plot— in the rθ plane. [PolarCoordsC.mw] Further examples of interesting graphs one can make are shown in figure 3.12. Experiment with changing the values of a, b, and t. The last plot is a lemniscate. See also PolarCoordsD.mw—no figure for this worksheet.

Figure 3.12. Rose plots.

3-13

Maple

3.12 Implicit plots The plot command works with expressions not with equations. When x and y are related by an equation, one must use the implicitplot command. The equation of a unit circle x 2 + y 2 = 1 shows the implicit relationship between x and y. In this case we can rearrange the equation to make it explicit y = 1 − x 2 and this could be used with the plot command. But some implicit equations cannot be made explicit. This is where the implicitplot command comes in. The basic syntax is implicitplot(expr, x=a…b, y = c(x)…d(x), options) where x and y are variables, a and b are real constants, c(x) and d(x) are expressions that evaluate to real constants for a fixed value of x. implicitplot has its own extensive set of options and many of the plot options may also be used. [Implicit.mw] We begin by graphing a circle and then graphing three concentric circles, see figure 3.13.

Figure 3.13. Implicit plots of circles.

Figure 3.14. An implicit and a polar plot of a strophoid.

3-14

Maple

Figure 3.15. Plot animation.

The single circle was generated with: c := x^2 + y^2 = 20: implicitplot(c, x = −10 … 10, y = −10 … 10); The first graph of concentric circles by: fn :={(x^2 + y^2 − 1), (x^2 + y^2 −.5), (x^2 + y^2 −.25)}; implicitplot(fn, x = −2 … 2,

3-15

Maple

Figure 3.16. Demonstration of the explore command.

y = −2 … 2). Note how ragged the circles are. We can improve on this by requiring Maple to use more points when graphing: implicitplot(fn, x = −2 … 2, y = −2 … 2, grid = [50, 50]). The default grid is [26, 26]. Be aware that the implicitplot command can gobble up computer memory. [Strop1.mw and Strop2.mw] A final example is shown in figure 3.14. To the left is an implicit plot but in a true strophoid there is no discontinuity at the origin. The

3-16

Maple

Figure 3.17. Demonstration of beats.

3-17

Maple

Figure 3.18. Example of dualaxesplot.

reader may wish to experiment with a larger grid. To the right is a plot using polar coordinates that generates the same curve—and it has no discontinuity. Moral: use implicit plots only when essential!

3.13 Animated plots [Animate.mw] The animation feature in Maple can be very informative. Figure 3.15 shows a worksheet with several animation commands (only two are shown in the figure). Note that the package plots is required. The user should click on a plot and observe that the context Animation icon has been selected; to the left are the play buttons. The reader is encouraged to click these to observe the animation. More details on the animate command may be found at https://www.maplesoft.com/ support/help/maple/view.aspx?path=plots%2fanimate.

3.14 Exploring with the Explore command [VertexExplore.mw] The Explore command takes animation to a further level. The worksheet (figure 3.16) shows a parabola in the form y = (x − h)2 + k with controls 3-18

Maple

Figure 3.19. A 3D plot.

to change the values of h and k. As the values change the parabola is replotted. The Explore command may be hard to see in the figure: Explore(plot((x − h)^2 + k, x = −20 … 20, y = −100 … 100), parameters = [[h = −10 … 10, label = â Term hâ ], [k = −50 … 50, label = â Term kâ ]], initialvalues = [h = 0, k = 0]). Full details of the command are found at https://www.maplesoft.com/support/help/maple/view.aspx?path=Explore.

3-19

Maple

Figure 3.20. A 3D implicit plot.

[Beats.mw] is another worksheet demonstrating Explore. In this, a plot is made of the addition of two sine waves having different amplitudes and frequencies. Figure 3.17 shows the beats that result. The parameters of wave A are defined outside the Explore command while the amplitude and frequency of wave B are defined only within the command. Any assignment of values to ampB or freqB outside the Explore will result in errors.

3.15 Plot with two axes [DualPlot.mw] When plotting two expressions, it is sometimes necessary to use two vertical axes when the vertical ranges of the expressions are very different. The dualaxesplot command covers this problem very well. Figure 3.18 shows an example.

3.16 Three-dimensional plots We end this chapter with some examples of 3D plots. Figures 3.19–3.21 show the worksheets Plot3d.mw, Sphere.mw and SpaceCurve.mw, respectively. When one

3-20

Maple

Figure 3.21. Spacecurve and tubeplot examples.

clicks a 3D plot the cursor becomes a curved arrow—see top plot in figure 3.19. The user can drag the arrow to change the orientation of the plot. Without the parameter color-blue, the color of the curve in the top plot of figure 3.21 would have varied with the z-value.

3-21

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 4 Solving equations and systems of equations

4.1 The solve command The solve command has the syntax solve(equations, variables) where equations can be one equation or inequality, or a set of equations or inequalities, and the optional variables is a name of a set or list of names for which to solve. We say that solve finds exact roots, meaning the results will be displayed with radicals when appropriate. [Solve1.mw] As seen in figure 4.1, the output may be an exact numeric, symbolic, a set, or a message indicating that no solution was found. Some observations: (1) The first two statements give the same answer; the equation has only one unknown, so the naming of the variable x was superfluous. (2) The third and fourth statements are equivalent, since by default Maple assumes the expression equals zero. In these outputs, I is Maple’s way of indicating √–1. (3) Outputs (5) and (6) show solve is capable of finding symbolic solutions. (4) When wrapped in curly braces, solve puts the results in a set. Output (8) shows how to access one of the roots. (5) For this preliminary look at Maple, we will say that the result in the last statement tells us that solve cannot get a result. Note that the plot shows that a solution does exist—advanced mathematics (the rational root theorem) explains solve’s problem with this quintic expression. [Solve2.mw] We wish to find the intersection of two curves. The plot in figure 4.2 shows that there are three solutions to f = g. The solve command has no trouble finding them; the evalf statement gives us the results in floating-point number making it easier to compare with the plot. Then we use eval statements to show that the two functions do in fact equal one another. The very slight difference for the third result comes about from rounding errors and would normally be of no concern. If the worksheet began with Digits:=25, the difference would be even less.

doi:10.1088/2053-2571/ab0bb3ch4

4-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 4.1. Simple examples of solve.

4-2

Maple

Figure 4.2. Another solve example.

4.2 Solving inequalities [Solve3.mw] The task is to solve 3x + 2y ⩽ 6 and 2y − x ⩽ 4. The solve command finds three solutions that are a little difficult to interpret—figure 4.3. A plot is made using the inequal command (this requires that the plots package be loaded). To limit the plot to only positive values of x and y, we add two more inequalities. In the plot, the line with a positive slope is −x + 2y = 4 (or x = 2y − 4), the one with the negative slope is 3x + 2y = 6 (or x = 2 − 2y/3). These intersect at (1/2, 9/4). The first result in

4-3

Maple

Figure 4.3. Example of solving with inequalities.

r corresponds to the part of the first line that touches the shaded area; the third result corresponds to the part of the second line that touches the shaded area. Maple has an LPSolve package for linear programming but that is beyond the scope of the present book.

4.3 Stress analysis [Stress.mw] This worksheet demonstrates a practical use of the solve command. Consider the structure represented by figure 4.4 with a weight of 10 000 N hanging 4-4

Maple

Figure 4.4. Framework for stress analysis.

Table 4.1. Resolution of forces.

Joint

Horizontal

1 2

− F1 + −

Vertical

2 f + f2 = 2 1 2 3 f + 2 f4 = 0 2 1

3

− f2 + f5 = 0

4



3 f 2 4

0

2 f − F2 = 0 2 1 2 1 − 2 f1 − f3 − 2 f4 1 f 2 4

− f5 = 0

=0

f3 = 10 000

− F3 = 0

from joint 3. We will assume the members of the structure are massless and are freely jointed one to another. Our task is to find the stress in each member. For equilibrium, at each joint the sum of the horizontal and the sum of the vertical components of all forces must be zero. From this we develop the equations shown in the table 4.1 below the diagram. We will assume every member is in tension, so the forces act away from each joint. In the solution, a negative value indicates compression. Figure 4.5 shows the completed worksheet. The terms a and b have been assigned to save having to enter their expression numerous times in the eq1…eq8 expressions. Remembering this old computer adage of garbage-in-garbage-out (for example, a sign type on the equations would still give results but incorrect ones) we do a check to ensure the net vertical force is zero.

4.4 The assign command [Stress2.mw] In figure 4.5 the op command was used to extract the values of the variables. In figure 4.6 the assign command is used. One assign command has replaced eight ops commands! Output (2) is not required—it is used here for illustration. [StressLinAlg.mw] While the solve command can readily find the roots for this problem, it may interest some readers to see the same results obtained using linear algebra—no figure is offered here. 4-5

Maple

Figure 4.5. Stress analysis.

4.5 The fsolve command In figure 4.1 we saw that solve was not successful in finding the roots of a quintic expression. This is a result of the Abel–Ruffini theorem that states that there is no algebraic solution—that is, solution in radicals—to the general polynomial equations of degree five or higher with arbitrary coefficients. For such polynomials, numerical methods are required. Remember that the results will be approximate. Note that the Abel–Ruffini theorem is a general statement. Clearly the polynomial resulting from an expansion of (x − 4)(x + 6)(2x + 3)(4x − 5) can be

4-6

Maple

Figure 4.6. The assign command.

factorized, so solve would find the four roots of 8x 4 + 18x 3 − 203x 2 − 78x + 360. So some higher-order polynomial will work with solve while others require fsolve. [Fsolve1.mw] The quintic x 5 − x 4 − x + 1 can be factored as shown in figure 4.7; hence its roots can be found with solve—we have not bothered with this. The roots of the next quintic x 5 − x + 1 cannot be found1 with solve but fsolve finds a single root. It is always advisable to check a root found this way. Setting x equal to the reported root gives a result of 2.4 × 10−9 with the default Digits setting, and zero with Digits:=25. [Fsolve2.mw] With polynomials, fsolve generally gives all possible roots while with a transcendental expression it is satisfied with finding just one. This is shown in figure 4.8. Further roots can be found if one has a clue as to their approximate locations. The plot shows two equalities in the range −3 < x < 5. The fsolve, with no set range, found just one solution. Using a statement in the form fsolve(expr, x=v1…v2) the other solution can also be located exactly. The subs command (short for

1 To quote Maple Help: The function RootOf is a placeholder for representing all the roots of an equation in one variable. See section 4.6 for more on this topic.

4-7

Maple

Figure 4.7. Example of fsolve at work.

substitution) shows that the two solutions do make the expressions equal within the acceptable precision limits (figure 4.9).

4.6 Systems of equations with fsolve [Fsolve3.mw] This worksheet (see figure 4.10) solves a system of two equations in x and y. Having assigned names to each equation, the worksheet uses solve to put them in the form y = f(x). This allows us to get a plot and see the approximate location of the roots. The first fsolve statement (without a specified range) finds a root near x = 16. We could have used a statement with a range as in r1 := fsolve ({eq1, eq2}, {x, y},x=12…18) since we can see from the plot there is a root near x = 16. The second fsolve uses a range to locate a root near x = 6.

4.7 Finding complex roots [Fsolve4.mw] From the plot2 in figure 4.11 we see that the real roots of the quartic function 3x4 − 16x3 − 3x2 + 13x + 16 lie at about x = 1.5 and x = 5.5. All the roots (two real and two complex) can be found with the solve command but in a very complicated form. Turning the results into floating-point values helps. We could, of course, combine the two operations using f1 := evalf(solve(eq1)). 2

The range y = −20…40 has caused the curve to be truncated but no useful information has been lost.

4-8

Maple

Figure 4.8. System of equations with fsolve.

The statement r1 := fsolve(eq1) finds both real roots, while r2 := fsolve(eq1,complex) finds all four. As we shall see in the next example, we may be less fortunate with transcendental expressions. [Fsolve5.mw] Figure 4.12 shows that when we look for the roots of exp(x) + sin(x) − 2, the statement r1 := fsolve(expr) finds the single real roots, but r2 := fsolve(expr,complex) finds only a single complex root and fails to report the real one. Recall that with transcendental expressions, fsolve is generally satisfied with just one result. When the solve command is used on the expression, a RootOf results. At this point we introduce a new command: allvalues, which can extract meaningful values from the RootOf result as seen in output (5). The second allvalues gives a more complicated output (6); but careful inspection reveals some useful information; for example, the first RootOf contains the real root 0.448 67. These roots are extracted with evalf commands and the results are put into the expression to show that they are all true roots. 4-9

Maple

Figure 4.9. How many roots?

4-10

Maple

Figure 4.10. System of equations.

[Fsolve6.mw] However, this is not the whole story. There are many complex roots for this expression as revealed in figure 4.13 but the RootFinding-Analytic command is too advanced for a detailed exploration in the present text.

4.8 Restricting the root to a range [Equilib.mw] When steam is heated to a high temperature, dissociation occurs. Let x be the mole fraction of water that has dissociated, p the total pressure of the system, and K the equilibrium constant.

2H2O ⇄ 2H2 + O2K 2 =

x2 2p · 2 (1 − x ) 2+x

At the working temperature we are told that K = 0.045 and p = 2 atms; our task is to find x. The worksheet shown in figure 4.14 demonstrates two ways. The first way solves the Q equation to get three values of x, but only values that satisfy 0 < x < 1 are physically meaningful. The result satisfying this is found by visual inspection to

4-11

Maple

Figure 4.11. Finding complex roots.

4-12

Maple

Figure 4.12. An incomplete fsolve search for complex roots.

Figure 4.13. Another way to find all the roots.

4-13

Maple

Figure 4.14. Restricting outputs from solve.

Figure 4.15. Example of isolve.

be the first of the three. In the second method, the solution is restricted to values that satisfy 0 < x < 1. Recall that solve can work with equalities and inequalities. In each case we extract the x value such that it may be used in subsequent calculations, if needed.

4.9 Example of using isolve [Isolve.mw] The isolve command is used to get integer solutions. Figure 4.15 shows a simple example; clearly there are multiple solutions to 3x − 4y = 7. That is what the 4-14

Maple

Figure 4.16. Isolve used to balance a chemical equation.

output (1) is telling us; _Z1 can be any value. The worksheet checks values of 1 and 2 for _Z1. We may use a second parameter in the isolve command to replace the name _Z1 by another name; in the next worksheet z is used. [Balance.mw] As a practical example of isolve, figure 4.16 shows a worksheet that balances a chemical equation. The equations of Fe, Mn, etc, reflect the fact that the number of atoms on each side must be the same. Note the use of Ox because the name O is reserved. There are six unknowns but only five equations so there is no unique solution. However, chemists like to use the lowest possible integer values, so we set z to 1.

4.10 Off to Mars [Saturn.mw] The speed v of a Saturn V rocket3 in vertical flight near the surface of Earth can be approximated by

⎛ M0 ⎞ v = u · ln ⎜ ⎟ − gt ⎝ M0 − mṫ ⎠

3 Kiusalaas J 2004 Numerical Methods in Engineering with Matlab® (Cambridge, UK: Cambridge University Press).

4-15

Maple

Figure 4.17. Saturn rocket velocity.

where: u = 2510 m s−1 = velocity of exhaust relative to the rocket, M0 = 2.8 × 106 kg = mass of rocket at lift-off, ṁ = 13.3 × 103 kg s−1 = rate of fuel consumption, g = 9.81 m s−2 = gravitational acceleration, t = time measured from lift-off. Determine the time when the rocket reaches the speed of sound (335 m s−1). The worksheet in figure 4.17 again shows that solve will often find multiple roots but fsolve gives only one when working on transcendental equations. The worksheet shows how to extract just the positive solution for tt as found by tt := solve({t > 0, v = 335}). Two methods of testing the results are shown. The fsolve command cannot work with tt := fsolve({t > 0, v = 335}).

4-16

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 5 Using units and physical constants

5.1 Some basic examples [BasicUnitsA.mw] Figure 5.1 shows some basic commands for working with units. In the second statement the Units command is used to assign a unit (in this case, centimeter) to the x variable. The commands combine and simplify display x with units of meter since that is the default unit of length. The unit associated with a variable may be changed using convert. Normally, the with(Units) statement would be placed right after restart. It has been delayed here to show that some work is possible without it. However, without it, the output for c would have been 12.2 m + 3.0 cm. Variable x is assigned a unit with the Unit command; the Unit pallet has been used for other variables. The units (m, cm and nm) are added by positioning the cursor just to the right of the number, opening the Units pallet (shown as an insert in the figure) and clicking the blue unit. Then one types the unit abbreviation inside the double brackets, for example [[km]]. Use the right arrow key to complete the work; the double brackets disappear. If the required unit (for example, m) is displayed in the pallet, the user can click on it. The command Units:-UseUnit(cm) changes the default unit of length from meters to centimeters. This is followed by some examples. The final statement shows how we can go from SI units to US customary units, which Maple called the FPS (foot pound second) system. [BasicUnitsB.mw] Figure 5.2 shows a worksheet where the user prefers to work in FPS units. This is accomplished with Units[UseSystem](FPS) followed by (Units [Standard]). Note one cannot abbreviate inch to in since in has another meaning in Maple.

5.2 Examples of usage The use of units is demonstrated by solving the telescope problem of chapter 1 in various ways. To recap: A telescope is used to observe, at a distance of 10 km, two doi:10.1088/2053-2571/ab0bb3ch5

5-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 5.1. Basic commands with units.

objects that are 12 cm apart and illuminated by light of wavelength 600 nm. Estimate the diameter of the objective lens of the telescope if it can just resolve the two objects. The relevant formula for this is Rayleigh’s criterion: two point objects making an angular resolution of θ are distinguishable if the diameter D of the telescope satisfies D ⩾ 1.22λ/θ provided D ≫ λ, which will be true for telescopes. We use the geometric approximation θ = s/z where z is the distance from the object to the objective lens and s is the separation of the two objects and z ≫ s.

5-2

Maple

Figure 5.2. Working in the FPS system of units.

[TelescopeUnitsDocMode.mw] Figure 5.3 shows a document mode worksheet. Note that we need to load the Units package. After typing Diam in the last statement, right click the first numerical expression (the one with the numerator of 732) and in the context menu use Simplify ∣ Simplify. Right click the second value (0.061 00… m), in the context menu use Units ∣ Replace, and put cm in the resulting dialog. Format output of last operation to 2 decimal places. [TelescopeUnits] figure 5.4 shows a worksheet mode file. Note the syntax of the convert command to change from meters to centimeters.

5.3 Using the Units command [TelescopeUnits2] Figure 5.5 demonstrates the use of the Units command with the variable assignment before the formulas to be used. In this figure the equations come first. The result requires the use of the eval command; in this the set {lambda…, s……, I ….} is used to replace variables in Diam by dimensioned numeric quantities.

5-3

Maple

Figure 5.3. Document mode file.

Figure 5.4. Worksheet mode.

Clearly, method A is easier. The results in both methods would benefit from formatting.

5.4 Temperature conversions [Temperature.mw] It is essential to differentiate between absolute temperature (what is −30 °C in °F?) and relative temperature changes (a room temperature increases by 20 °F, what is the equivalent in °C?) Examples are shown in figure 5.6. Typing ?UnitsCalculator in a worksheet opens a conversion dialog. Figure 5.7 shows this being used to convert 100 °C (absolute scale) to Fahrenheit. Note the

5-4

Maple

Figure 5.5. Example of Units command.

Figure 5.6. Temperature conversions.

5-5

Maple

Figure 5.7. Example of the conversion dialog.

Figure 5.8. Working with scientific constants.

5-6

Maple

Figure 5.9. Force of gravity.

box reading temperature (absolute). The dialog can be used for many other conversions.

5.5 Physical constants [SciConstants.mw] Typing ?PhysicalConstants in a worksheet will open the Maple Help listing all the physical constants available. Figure 5.8 shows some simple examples of working with scientific constants.

5.6 Gravity constants G and g [Kilo.mw] In this worksheet we estimate the force exerted by a 1 kg mass at sea-level, comparing results from F1 = G·M2·m and F2 = mg where G is the Newtonian gravitaR tional constant, I is the mass of the Earth, R the radius of the Earth, g is the acceleration due to gravity, and m is 1.0 kg. Figure 5.9 shows the results, which are not quite the same (9.792 81 and 9.806 65). Stay calm and carry on: Maple is not at

5-7

Maple

Figure 5.10. Pump problem with units.

fault; the value of g is defined1 to be exactly 9.806 65 without reference to the values of G, M and R.

5.7 Pump problem revisited [PumpWithUnits.mw] In chapter 2 we looked at this problem: Water is pumped at a rate of 0.25 m3 s−1 from a well that is 25 m deep. At the pump output the water has a velocity of 8.5 m s−1. If the efficiency of the electric pump is 80%, how much power does it draw? figure 5.10 shows the document mode worksheet with units.

1 Defined by the 3rd meeting, in 1901, of the General Conference on Weights and Measures (Conférence Générale des Poids et Mesures, CGPM).

5-8

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 6 Linear algebra

6.1 Matrices and vectors [MatrixStart.mw] There are several ways of defining a matrix and adding values to it. The first uses the Matrix palette. The palette is shown to the left in figure 6.1; the user can alter the numbers of rows and/or columns before clicking Insert Matrix. The top left of the figure shows the resulting matrix with a placeholder. The user enters values in each of these, navigating using the Tab key, to get a result similar to the lower left image in the figure. The user could have first entered A:= and then followed the procedure with the cursor in the appropriate position. Specifying either 1 row or 1 column in the palette, a user may construct a row or column vector. The results are shown in the first two statements after restart in figure 6.2. Maple displays the elements of a matrix that is 10 by 10 or smaller, and vectors up to 10 by 1. Placeholders are displayed for larger structures. The second method is with the Matrix command. The statement B:=Matrix (2,3) generates a 2 by 3 matrix filled with zero elements. If just one parameter is used, a square matrix results; so B:=Matrix(3,3) and B:=Matrix(3) are equivalent. Elements may be entered with statements such as B[1,1] := 2. See outputs (1) and (2) in figure 6.2. The command B:=Matrix(4,shape=identity) makes a 4 by 4 identity matrix. A list of lists may be used to construct a matrix with elements in place, for example C := Matrix([[1, 2, 3], [4, 5, 6]]); see output (3). To learn about more options for the Matrix command, type ?matrix in a worksheet. Similarly, the command Vector(2) constructs a 2 row vector of zeros, while Vector[row]([5,6,7] makes a row vector with elements 5, 6 and 7: see output (4) and (5)). In addition, 〈5, 6, 7〉 and 〈5∣6∣7〉 generate a column and a row vector, respectively, as seen in outputs (6) and (7), Vector elements may be changed with statements like L[2]:=7. For more details, use the command ?vector. The 〈 〉 method also works with a matrix—see output (8).

doi:10.1088/2053-2571/ab0bb3ch6

6-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 6.1. Using the palette to define a matrix.

6.2 Simple matrix and vector math [SimpleMath.mw] Figure 6.3 demonstrates some simple mathematical operations on matrices and vectors. Note that we do not try to multiply them in this worksheet— that operation requires the package LinearAlgebra. With A and B assigned to two 2 by 2 matrices, we use A+B to add the elements and generate a new matrix C—output (3). In output (4) a constant has been subtracted from matrix C with C−z. We can also add divide and multiple by a constant. Multiplication is shown in output (5); the order of the operands (A * q or q * A) is immaterial. In subsequent statements similar operations are applied to vectors. One important difference is that to add a constant to each element the operand must be +~, not just the + symbol—output (7). Outputs (8) and (9) show that when we revert to floating-point math, round-off errors may occur.

6.3 Linear algebra This text will use The LinearAlgebra and VectorCalculus packages, which replace the deprecated linalg package. Readers may find texts and/or websites using linalg; please note that many command names have changed, for example matrix is Matrix in the newer package, multiple is Multiply, and the nice short charpoly is replaced by the lengthy CharacteristicPolynomial, etc. Tip: To save typing (and typo errors), enter the first few letters of a command or package name. When the correct ‘cool tip’ appears, press the ESC key, and select what is needed from the dialog box that appears. [LinearAlg1.mw] This worksheet demonstrates some simple matrix math—figure 6.4.

6.4 Solving a system of equations [LinearAlg2.mw] It can be shown that if M is a matrix whose elements are the coefficients of the equations, X is a vector of the unknowns and C is a vector of the constants, then the equations may be written in matrix form as MX = C. We cannot write X = C/M but we may write X = M−1C, where M−1 is the matrix inverse of M. 6-2

Maple

Figure 6.2. Commands to generate a matrix or a vector.

Figure 6.5 shows a worksheet used to solve a system of three equations. The print command is used just to remind us which value in Sol relates to which unknown. The tests’ values (below) demonstrate how to reference each solution value. Finally, we use the solve command to show that the two methods agree.

6-3

Maple

Figure 6.3. Simple math with matrices and vectors.

6-4

Maple

Figure 6.4. Examples of matrix math.

6-5

Maple

Figure 6.5. System of equations: Matrix solution.

It is tempting to state that, while the matrix method takes more work than the simple solve, the matrix method is pedagogically more transparent; solve is something of a ‘black-box’. But the MatrixInversion is even more of a ‘black-box.’ In chapter 4 the solve command on a framework problem; the file StressLinAlg.mw shows a matrix method for the same problem. [LinearAlg3.mw] The work setting up the matrix method can be reduced as shown in figure 6.6. In output (1) through (4) we see how the GenerateMatrix command saves the work of constructing the M matrix and V vector. The command LinearSolve saves finding the inverse and performing the multiplication. For readers more familiar with linear algebra we reduce the work even further by generating the augmented matrix: outputs (5) and (6). 6-6

Maple

Figure 6.6. Using GenerateMatrix and LinearSolve.

6-7

Maple

Figure 6.7. Example of eigenvectors and eigenvalues.

6.5 Introduction to eigenvectors and eigenvalues [Eigen1.mw] If A is a matrix, v a vector, and λ a number (i.e. a scalar quantity), which satisfy the condition Av = λv, then we say that v is an eigenvector of A with eigenvalue λ. When a vector v is multiplied by a scalar λ, the result is a vector with the same direction but a different magnitude (length)—longer if the λ > 1. In figure 6.7 we see that the matrix A has two eigenvectors and two eigenvalues; in each case the criteria is met. [Eigen2.mw] Given a matrix A how do we discover its eigenvectors and eigenvalues? While Maple can perform these calculations with little effort on the user’s part, it is instructive to see a worked example where the user does most of the work. In figure 6.8 we begin by defining the matrix A whose eigenvalues and eigenvector are to be found. We also define I as the identify matrix; we could have, more simply, used I:=IdentityMatrix(3). The criteria Av = λv can be written as (λI − A) = 0; we find the determinant of (λI − A) in output (1). Solving this gives us λ1 = 1 and λ2 = −3. The vector corresponding to each λ must satisfy the equations

6-8

Maple

Figure 6.8. Finding the eigenvalues and eigenvectors.

(5 − λ)v1 + 8v2 + 16v3 = 0 4v1 + (1 − λ)v2 + 8v3 = 0 − 4v1 − 4v2 + ( −11 − λ)v3 = 0 For λ = 1, these equations are displayed in output (4). We cannot truly solve these since the determinant of (λI − A) is zero. But we can find the relative values of v1, v2 and v3 as shown in output (5); letting v3 = 1 we see that v1 = −2 and v2 = −1, allowing 6-9

Maple

Figure 6.9. Maple finds the eigenvalues and eigenvectors.

6-10

Maple

us to manually assign values to the elements of eigenvector V (output (7)). In output (8) we test Av = λv. After all this hard work we will not continue with λ2 = −3 but will let Maple do the work! [Eigen3.mw] Figure 6.9 shows a worksheet where Maple finds the eigenvalues and eigenvectors of the same matrix previously worked on. The command Eigenvalues produces an output that, at first glance, is hard to understand. The first part of the output is a vector with the three eigenvalues; we separate this in output (2). The second part (separated in output (3)) is a matrix of eigenvectors. The first column of M is the eigenvector 〈−2, 0, 1〉 associated with the first eigenvalue of −3, and so on. Note that while λ = −3 occurs twice, the first and second eigenvectors are not the same.

Figure 6.10. Two rules about eigenvalues.

6-11

Maple

In output (3) we select the first eigenvalue and the first eigenvector; we test for Av = λv in output (4); in output (5) we do the same test for the third eigenvalue and the third eigenvector. Note how this agrees with the work done in figure 6.8. Output (6) shows the Eigenvalues command; it gives the same results as before. In (8) we see the characteristic equation of the matrix, which solves to give the same eigenvalues. [Eigen4.mw] Two rules about eigenvalues are: (1) the product of the eigenvalues equals the determinant of the matrix, and (2) the sum of the eigenvalues equals the sum of the main diagonal of the matrix (the trace). Figure 6.10 shows a worksheet demonstrating the rules. It also shows another way of getting at the vector (L) and matrix (M) using L,M:=Eigenvectors(A); output (1) gives the result, output (2)

Figure 6.11. The p-norm command.

6-12

Maple

Figure 6.12. DotProduct and CrossProduct.

merely reinforces the fact that L and M are separate names in the worksheet. When we perform elementwise operations on vectors, we follow the mathematical operator (+, −, *) by a tilde (~)—see the statement leading to outputs (3) and (4).

6.6 Notes on Maple vector commands [Vector1.mw] Unless otherwise stated, we will assume that each of our vectors is in a standard position, meaning that its initial point is at the origin (0, 0). The normal of a vector is simply its length. The LinearAlgebra package1 computes what is called the p-norm which is defined as p−norm = p ∑in= 1∣vi ∣ p . The symbol ∣v1∣ denotes the magnitude (i.e. length) of vector v1. The worksheet in figure 6.11 shows the results of p = 0 to 2 for the generalized vector A. Then it shows the results for a typical vector. When no p value is used (outputs (2) and (7)) the result is the value of the maximum element in the vector. With p = 0, one might at first assume the result is the number of elements but it is the number of non-zero elements—see output (8). With p = 1 we get the sum of the absolute values of the elements and with p = 2 we get the length (Euclidian length) of the vector. 1

The Norm command in the Physics[Vector] package is equivalent to p = 2 (the Euclidian) normal.

6-13

Maple

[Vector2.mw] The dot product of two vectors a and b having an included angle of θ is defined as a · b = ∣a∣∣b∣cos(θ ). To find this quantity we use the DotProduct(a,b) command; the result is a scalar. The cross product of two vectors is defined as a × b = ∣a∣∣b∣sin(θ ). To find this we use CrossProduct(a,b); the result is a vector. When a and b are a pair of 3d vectors, the cross product is a vector at right angles to the pair with magnitude equal to the area of the parallelogram spanned by a and b. The Maple command requires the two vectors to be at least 3d. Figure 6.12 shows the two commands for generalized vectors to demonstrate the formulas used. Output (3) shows how to find the equivalent of the cross product for a pair of 2d vectors.

6.7 Some vector calculations [Vector3.mw] Since Maple’s command DotProduct gives us a · b and the Norm command can be used to find ∣a∣ and ∣b∣ then, given two vectors, we can find the DotProduct(a, b ) included angle with cos(θ ) = ∣ aa∣∣·bb ∣ = Norm(a, 2) × Norm(b, 2) . Furthermore, since the

component of a in the direction of b is a cos(θ ) we may find this using DotProduct(a, b ) . In this worksheet (figure 6.13) we find the angle between component = Norm(b, 2)

Figure 6.13. Angle between the two vectors.

6-14

Maple

Figure 6.14. Area of parallelogram.

two vectors and the component of the first in the direction of the second. The first method computes the angle of each vector relative to the x-axis, and then subtracts one from the other to find the included angle. The second method uses the formula u ·v cos(θ ) = ∣ u ∣·∣ v ∣ where u and v are the two vectors. The differences in the 10th decimal places for outputs (1) and (2), and (3), and (4) result from rounding errors. [Vector4.mw] Our task is to find the area spanned by a = 〈3, −3, 1〉 and b = 〈4, 9, 2〉. Figure 6.14 shows a worksheet to perform the calculation. Of course, the two statements could have been combined as area := Norm(CrossProduct (a, b), 2).

6-15

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 7 Introduction to calculus

In this chapter we review some of the more elementary Maple commands for calculus work. In a later chapter the solution to ordinary differential equations is explored.

7.1 Looking for the limit [Limit.mw] Figure 7.1 shows a worksheet with some examples of the limit command. In the first statement we see that Limit (with capital L) is what Maple refers to as an inert command; it more or less displays its input. Inert commands are useful for documentation. The output (3) is a floating-point number due to the presence of evalf; without it the result was 1/11. In (6) the Calculus palette was used to construct the lim command. Statement (8) shows how to specify a direction (the limit as x → 0 from the left) either left or right. In the palette generated form, the user typed x=0to indicate from the left. Note that limit returns undefined when a limit cannot be computed. [Limit2.mw] Finally, we perform a limit on a function; the reader will recognize that this limit is the definition of differentiation. Figure 7.2 continues that theme in a document mode worksheet1 using Clickable Math. The first two expressions were entered2, then right-clicked and Execute and Display Inline was used; the shortcut for this is CTRL+=. The third and fourth expressions were entered and, from the context menu, the user selected Differentiate ∣ with respect to ∣ x.

7.2 Some differentiation examples [Diff1.mw] This worksheet displays some simple differential examples—figure 7.3. Output (2) again shows the use of an inert command, while (3) shows how to No file for this worksheet is included. The easiest way to get the first parameter in the second statement is to type g(x+h)/h then return to the numerator and insert the -g(x). 1 2

doi:10.1088/2053-2571/ab0bb3ch7

7-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 7.1. Examples of the limit command.

evaluate a differential at a point; first with eval and then with fdiff, which is a floating-point command. We see another way in section 7.4. Outputs (4) and (5) demonstrate how some simple problems may be solved. The last output (6) uses the palette to construct the differential operation.

7-2

Maple

Figure 7.2. Limit and differentiation.

Figure 7.3. Differentiation examples.

7-3

Maple

[Diff2.mw] This worksheet (figure 7.4) has examples of second and third differentials found using: i. diff multiple times either sequentially or nested—output (1), ii. a sequence like x, x for the differential variable, or the equivalent of x$2 where x is the variable and 2 is the number of times to differentiate, or with the palette operator—outputs (2) and (3), iii. The prime method in which f′’ and f″ are commands to differentiate the expression f once and twice, respectively—output (4). Note that f″ is the

Figure 7.4. Second and third differentials.

7-4

Maple

letter f followed by two single quotes; a double quote will not work! In output (5) the function g(x) is differentiated. Of course, f'(g(x)) is equivalent to diff(g(x),x).

7.3 The D operator [Diff3.mw] To quote from Maple’s Help: D is primarily a differentiation command, like diff, but it is more general than diff in two aspects: it can represent derivatives evaluated at a point and can differentiate procedures. Figure 7.5 shows a few simple examples. Output (1) shows the D operator working with two functions (ln and sin). Outputs (2) and (3) demonstrate that D fails with a simple expression but works with a function. Output (4) is the value of function df/dx evaluated at x = 5 found in two ways; the D method being much briefer. To complete the circle; solve (diff(f(x),x) = 12) will return the value 5.

7.4 Implicit differentiation [Diff4.mw] The worksheet in figure 7.6 introduces the implicitdiff command. The task is to find the slope of the curve at a specified point, given an expression in which x and y are related. This is done firstly without implicit differentiation (outputs (1) and (2)) and then with it (outputs (3) and (4)).

7.5 Examples of critical points The next two worksheets demonstrate solutions to some simple problems. [Diff5.mw] In this worksheet we find the vertex form of the quadratic equation but, recognizing the fact that the vertex occurs at an inflection point (dy/dx = 0), this

Figure 7.5. The D operator.

7-5

Maple

Figure 7.6. Implicit differentiation.

gives us the expression for h. Then we find the value of k by setting x → h and evaluating y. In figure 7.7, outputs (1) and (2) show these steps; in (3) we construct the vertex form and test that it is equivalent to the standard form. Output (4) uses the information thus found to get the vertex of y = 2x2 − 4x + 5. Finally, we perform the same calculation without reference to the previous work. This worksheet introduces the cat (short for concatenate) command and uses it in print statements. [Diff6.mw] This worksheet reveals how to find the critical points of an expression— figure 7.8. The first differential finds the x-values for the critical points. Maple finds four, but two are identical. The second differential is used to detect if a critical point is: (i) a local minimum (f″ > 0), (ii) a local maximum (f″ < 0), or (iii) an inflection point (f″ = 0 and the sign of f″ on the two sides of the point have opposite signs).

7.6 Some integration examples [Int1.mw] Figure 7.9 shows some simple integration examples. Output (1) demonstrates that Maple does not add the constant of integration, but the user can force this to appear. Clearly, it is better to use an indexed constant. Output (2) shows the use of 2D math; the integration symbol can be generated (a) from the Calculus palette or (b) by entering int, pressing the ESC key, and selecting Int (indefinite) from the pop-up dialog. Output (3) shows the integration of function f(x) and s(x); 7-6

Maple

Figure 7.7. Getting the vertex of a parabola.

this time the simple integration constant did appear at the end of the results. Output (4) results from the use of the inert command Int (note the capital I). The value command is illustrated in output (5).

7.7 Definite integrals [Int2.mw] Figure 7.10 shows some simple definite integrations. Output (1) reveals how to add limits when using the int command, that the inert Int works with definite integration, and that one can obtain the numeric value with evalf. Output (2) establishes that double integration can be performed in several ways, while output (4) shows that sometimes Maple needs a little help to give us a clear result—we also see a test that input → int → result → diff takes us full circle. [Int3.mw] In this worksheet (figure 7.11) output (1) illustrates that when the integral cannot be evaluated in closed form, Maple returns the unresolved expression. If we use evalf the numeric answer is obtained, since Maple then performs a numerical integration operation involving Riemann sums. There are times when Maple gives a result (outputs (2) and (5)) which involves functions, many 7-7

Maple

Figure 7.8. Critical points.

of which will be unfamiliar to readers. We resolve this in one of two ways: using evalf or by entering the integration limits with fixed-point values (i.e. 2.0 rather than 2); see outputs (4) and (6).

7.8 The assume command [Int4.mw] Sometimes a definite integral cannot be computed without giving Maple more information. The assume command is used for this. Figure 7.12 shows two ways of telling Maple to assume a constant (s) is greater than zero. Before being told to assume s > 0, Maple will essentially give us a definition of the integral. In earlier versions, before the output there would have been an error message: Definite integration: Can’t determine if the integral is convergent. Need to know sign of → s. Will now try indefinite integration and then take limits. In newer versions, the user is

7-8

Maple

Figure 7.9. Examples of indefinite integration.

assumed to be more knowledgeable. The last statement uses about to explain the meaning of s∼ in output (2).

7.9 Finding the area between two curves [AreaInt.mw] One definition of a definite integral of f(x) is that it evaluates the area under the curve of f(x) between the two limits. This is illustrated in figure 7.13 where the area between two curves is found.

7-9

Maple

Figure 7.10. Definite integrals.

Two functions (f(x) and g(x)) are defined; a plot gives a good idea of the location of the two intersection points. Using this approximate knowledge, the exact locations are found with fsolve. This enables a definite integral for the common area to be constructed and evaluated.

7.10 Introduction to ODEs [ODEInt.mw] The next chapter covers differential equations but the worksheet here x will serve as an introduction. A text book states that y = 3 − exp( − 2 ) is a solution 7-10

Maple

Figure 7.11. More complex results.

to the differential equation y′ = 1/2(3 − y ). The task is to verify this. In figure 7.14, the original ODE is entered as dy and the solution as sol. The solve command shows that exp(−x/2) = 3 − y. The sol expression is differentiated and 3 − y is substituted for exp(−x/2). The result is the same as the original ODE, thus proving the fact that the given solution is a correct3 one. 3

But not necessarily the only one.

7-11

Maple

Figure 7.12. The assume command.

Figure 7.13. Area between two curves.

7-12

Maple

Figure 7.14. Introduction to ODEs.

7-13

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 8 Differential equations

In this chapter, methods of solving differential equations are explored but we shall barely scrape the surface of Maple’s features in this field.

8.1 Initial value problems (IVPs) [IVP1.mw] In this worksheet (figure 8.1) we solve the initial value problem y′ = 2xy subject to the initial condition that y(0) = 3. This is really a pen-and-paper problem since one can simply do a separation of variables. [IVP2.mw] We solve a simple problem by employing Maple’s dsolve command1. Figure 8.2 shows dsolve will obtain the solution very efficiently. The plot command is used to graphically display the solution. Also included in the worksheet are examples of the DEplot command, which requires the DEtools package; we elected to use the ‘long form’ rather than loading the entire package. This command is more appropriate for a differential equation that has no analytical solution; DEplot uses a numerical integration method—more on this topic later in the chapter.

8.2 Entering ODEs and initial/boundary conditions [OdeInput.mw] Figure 8.3 shows various methods of entering ODEs and their initial or boundary conditions. It is important to note that output (4) has two errors: each y should be y(x). In output (5) the ODE and the conditions are separate expressions and must be made a set in dsolve. In output (6) the ODE and condition are assigned as a sequence, so they must be turned into a set in dsolve. In output (7) the ODE and its condition are assigned as a set, which is then referenced in dsolve.

1

Note that dsolve does not need DEtools.

doi:10.1088/2053-2571/ab0bb3ch8

8-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 8.1. A simple IVP.

8.3 Boundary value problems (BVPs) In boundary value problems one is given a differential equation and the values of the function and/or derivates at different points. Here a BVP problem is solved in three ways, the last being the most efficient. [BVP1.mw] Our task is to solve u″ = −(1 + x), u(0) = 0, u(1) = 0. In figure 8.4 we begin by defining the second-order differential u″ and integrating it twice to get an expression for u—output (1). The expression is turned into a function using the unapply command, output (2), to enable us to solve the function with u(0) = 0 and u (1) = 0, giving us values for the two integration constants (C1 and C2) in output (3). There is also an example of the use of the assign command. Finally, we test the result in output (4). [BVP2.mw] In this worksheet the same BVP is solved using the dsolve (differential solve) command. The differential equation is defined in output (1) of figure 8.5 and the result of solve in output (2). The worksheet continues as before. [BVP3.mw] In this worksheet (figure 8.6) the same BVP is solved again using the dsolve but this time we include the boundary conditions (bc)—output (2). This

8-2

Maple

Figure 8.2. Demonstrating dsolve and DEplot.

method finds the solution and evaluates the integration constants in a single step. The worksheet concludes with a test of the boundary conditions in two ways. The odetest command is expected to return zero2 when all is satisfactory; the odetest in

2

A non-zero result does not always imply a poor solution.

8-3

Maple

Figure 8.3. Examples of ODEs and conditions.

(4) returns three zeros: one for the test of sol/deq, and two for the boundary conditions.

8.4 Family of solutions [Family.mw] This worksheet (figure 8.7) demonstrates a method of plotting the curves of a family of solutions. The general solution contains a constant —C1 because we have given no initial condition. A sequence of values for —C1 equal to 1–5 is generated; see output (4). This sequence is then plotted: note the need to include fam in square parentheses. If one wishes to be economical with statements, (3) and (4) may be omitted and the plot generated with plot([seq(rhs(sol), _C1 = 1..5)], t = 0..10).

8.5 Numerical integration Some differential equations have no closed form (i.e. analytical) solution. Numerical analysis textbooks show how to get approximations for such equations. A popular 8-4

Maple

Figure 8.4. BVP method 1.

method is the fourth-order Runge–Kutta (RK4) approach. Generally, one allows Maple to select the method; it frequently defaults to the Runge–Kutta–Fehlberg (RKF45) algorithm. Briefly, a numerical differential solver starts the initial condition y(x0) = c and computes an approximation for y(x0 + h) where h is a small number. It repeats the process to find y(x0 + 2h) and so on. [Num1.mw] The first worksheet demonstrates the use of the numeric option in dsolve for an ODE that can be solved analytically but where the result is rather daunting. In figure 8.8, output (1) gives the analytical result for the ODE y = 2y + exp(−2(t − 6)2) with initial condition y(0) = 1. The solution expression sol1 is turned into the sol2 function which is evaluated3 for x = 0 and x = 2. The statement leading to output (3) uses the numeric option within the dsolve parameters and specifies the range of the x-value for which a solution is required. The result sol3:= proc x_rkf45 ... end proc is a procedure4 that is a small computer program, the

3 4

The command sol2(0) does not require the evalf command since y(0) is defined as 1 by the initial condition. Procedures are explained in chapter 9.

8-5

Maple

Figure 8.5. BVP method 2.

workings of which are not displayed but represented by the ellipses. The procedure can be called to find the solution value at a given x-value. Output (4) exemplifies the use of the Array parameter to generate solution values for various x-values. The plots from the analytical and the numerical methods are the same. Note that to plot the results from the numerical method the odeplot command was used; this is part of the plots package. [Num2.mw] This worksheet (figure 8.9) shows a second-order ODE which has no closed form solution. The first statement is a sequence of the ODE and its initial value. The second statement calls for an analytical solution but generates no result and no error message, thereby indicating there is no closed form solution. The third statement specifies a numerical solution; since the range option is not included Maple uses the default value −10 ⩽ x ⩽ 10. The resulting procedure is used to find solution values at x = 0, 0, 5 and 1. The solution is also used for the plot5. Then an array of y-values is requested in the last statement. In both cases the output displays values for x, y and dy/dx.

5 It would be inappropriate to use odeplot(ans2); it would result in a series of straight lines joining the points from the array.

8-6

Maple

Figure 8.6. BVP method 3.

[Num3.mw] This worksheet (figure 8.10) shows another second-order ODE. It is solved analytically (solution in sol) and numerically (solution in sol2). Various way of extracting solutions for specified values of x are shown; of particular interest is the option Array in the last output. dx [Num4.mw] Our final numerical example is to solve = sin(x + t ) · dt cos(x − t ) · exp(2t ), x(0) = 1. Figure 8.11 shows a worksheet with three versions of dsolve. The first gives a warning that it cannot evaluate a solution for t > 5.36. In the second a maxfun (maximum functions) parameter has been added and now Maple is able to get as far as 8.85. In the first two, the required range of t is from 0 to 10; in the third dsolve this is reduced to 0 to 4; no error message results and a procedure is returned. Please note that this worksheet takes several minutes to recalculate. [Num5.mw] In this worksheet (figure 8.12) the same ODE is solved using the stiff parameter. In Num4.mw, the resulting procedure uses the RKF45 method but in Num5.mw the Rosenbrock method is used. Most experts state that this gives a poorer approximation, but the worksheet recalculates it in a reasonable time compared to Num4.mw.

8.6 The simple pendulum The differential equation for a simple pendulum is

8-7

g d2θ + sin(θ ) = 0. 2 dt L

Maple

Figure 8.7. Plotting a family of solutions.

[Pendulum.mw] General physics texts assume the amplitude is small; i.e. the pendulum is released with a small θ value. This means that sin(θ) can be approximated by just θ. The Maple worksheet for a 0.75 m pendulum, started from θ = 0.4 radians6 (≈23°), is shown in figure 8.13. There is no need to use the numerical approach here. 6

Note sin(0.4) = 0.389 so the approximation sin(θ) ≈ θ is acceptable.

8-8

Maple

Figure 8.8. Analytical and numerical solutions.

8-9

Maple

Figure 8.9. ODE with no analytical solution.

[Pendulum2.mw] To model a large amplitude pendulum we must resort to a numerical method as illustrated in figure 8.14. The pendulum length remains at 0.75 m but the initial θ value is 2 radians (≈72°).

8.7 Coupled ODEs [Radio.mw] As an example of coupled differential equations, consider a radioactive element (P) that decays to element D, which is itself radioactive. It is customary to

8-10

Maple

Figure 8.10. Numerical integration.

refer to these as the parent and daughter elements in a decay series. The Bateman dN dND equations for this situation are: A = −λANA and = −λDND + λANA where the dt dt λ terms are the reaction rates and are related to half-lives t½ by the equation λ · t½ = ln(2). In the example let NP(0) = 200, λP = 10 years, ND(0) = 0, λD = 1 year. Figure 8.15 shows the worksheet. 8-11

Maple

Figure 8.11. A difficult ODE.

8.8 Singular and general solutions [Singular.mw] The dsolve command finds the general solution to an ODE but sometimes there is a singular solution. In figure 8.16 we find the general solution (output (2)) to the ODE in output (1). Oddly, output (2) has the term 2_Cl1 twice,

8-12

Maple

Figure 8.12. A stiff ODE.

but as _Cl1 is a constant so is 2_Cl1; so in output (3) with the subs command, we replace 2_Cl1 by a simple c. We have reason to believe that y(x) = x is also a solution. Output (4) tests the assertion that y(x) = x can be obtained from the general solution. This output cannot be true since it would require 2 = 0, thus disproving the assumption. But in (5) and (6), where y(x) in the ODE is replaced by x, we get 1 = 1. Conclusion y(x) = x is not part of the general solution, but it is a solution; for this reason it is described as being a singular solution.

8.9 Direction fields [Field1.mw] This worksheet (figure 8.17) demonstrates the use of the dfieldplot command. Used on its own this command will plot the direction field of a differential equation. If we solve that equation and plot the result, then we may use display to see both the direction field and the solution.

8-13

Maple

Figure 8.13. Small amplitude pendulum.

[Field2.mw] This worksheet (figure 8.18) illustrates the use of the DEplot command. The command solves the differential using a numerical method; the default is RKF45 but the method option allows the user control over this. We have used the syntax DEplot(deqns, vars, trange, inits, options) where deqns is a list or set

8-14

Maple

Figure 8.14. Large amplitude pendulum.

8-15

Maple

Figure 8.15. Pair of coupled ODEs.

of ordinary differential equations, or a single differential equation, vars is the dependent variable (or a list or set thereof), trange is the range of the independent variable, and inits is a list or set of the initial conditions (note that even with just one condition, it needs to be in a list or set). For more on options enter ?DEplot in a worksheet.

8-16

Maple

Figure 8.16. Testing a proposed singular solution.

Figure 8.17. Using dfieldplot.

8-17

Maple

Figure 8.18. Using DEplot.

[Field3.mw] This worksheet (figure 8.19) shows an alternative method of specifying the initial conditions using a list of points rather than an equation. In the top graph the command has generated three solutions7 curves: one for each initial condition. The syntax is: DEplot(deqns, vars, trange, inits, xrange, yrange, options); where xrange is the range of the first dependent variable, and yrange the range of the second independent variable (as we have only one independent variable, this is 7

Had we used just [0, 10] the plot would have been the same in the lower graph in figure 8.17.

8-18

Maple

Figure 8.19. Getting a family of solutions.

omitted). If we wished to see only the family of solution curves, we could replace arrows = thin by arrows = none. In the second DEplot command the init parameter is omitted8; this results in a graph with just the direction field.

8

At least one of the init and the xrange parameters must be specified in a DEplot statement.

8-19

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 9 Procedures

In chapter 1 we saw how to define a simple function with statements like f := x → x2 + 3x − 4. Procedures allow us to develop more complicated user-defined functions.

9.1 Programming structures Thinking back to CompSci 101, we will recall that computer programs use three structures: (1) sequential (the program starts at the top and executes one statement after the other), (2) branching or selection (depending on the value of an expression, the program executes one set of statements or another), and (3) looping (a set of statements is repeated a set number of times or until an expression satisfies a condition). Programming structures may be nested within each other. The only branching structure in Maple is the if…else.end if with the syntax.1 if then | elif then | | else | end if

where phrases within ∣ ∣ are optional. The conditional expression can take several forms such as: (i) a = 12, (ii) a + b >= 10, (iii) a 0 and b = 3. The permitted relational operators are: a), but the code cannot alter the value of a formal parameter (e.g. a:=a+2 is not permitted), rather one must work with a local variable. If the procedure has a code such as for j from 1 to 10, and j has not been declared local, then Maple will issue a warning that j has been assumed to be local. 3

Maple 2018 also permits one to use a do…until structure.

9-2

Maple

Figure 9.1. Exemplars of IF, FOR and WHILE.

[Prog2.mw] In this worksheet (figure 9.2) the conditional structures of Prog1.mw are turned into procedures, which can be called whenever needed with different starting values. Here we see examples of the description option and a local variable. In the second procedure the statement before end proc reads ans. As this is the 9-3

Maple

Figure 9.2. Local and global variables.

last statement within the procedure, the procedure will return the value of ans. The command cat is short for concatenation—the joining of text and the values of variables. [Prog3.mw] In this worksheet (figure 9.3) the looping structures of Prog1.mw are turned into procedures. [Prog4.mw] Here we examine the use of the return statement within a procedure. In this worksheet (figure 9.4) the second looping structures of Prog3.mw are coded in a different way. The syntax shown above for the while structure is not the whole story; parts of it are optional. We can in fact make a do…end do structure as seen in the figure. This looks as if it would iterate repeatedly. It would, but for the return statement (figure 9.5). This statement tells the procedure what it is to return and then ends the procedure (and, of course, it has included the do…end do loop).

9.4 Several ways to find the GCD Maple has a command gcd to find the greatest common divisor of two integers, however we will make our own versions since the exercise will provide some insights into coding procedures. There are two commonly used algorithms4 for finding the GCD: Euclid’s subtraction method and Euclid’s division method. Figure 9.6 illustrates the two methods. The subtraction method requires the integers to be positive. [GCD1.mw] Figure 9.7 shows an implementation of the subtraction method. Our results agree with Maple’s gcd command. Our procedure traps a negative value as an 4

See, for example, https://en.wikipedia.org/wiki/Euclidean_algorithm.

9-4

Maple

Figure 9.3. Two procedures with conditional structures.

error. Within the parameter declaration the double-colon operator (::) is used to specify that only integers are valid parameters; the last call to GCD shows what happens when a non-integer is supplied. This type of declaration could be used to advantage in all the GCD procedures shown in this section. [GCD2.mw] Figure 9.8 shows an implementation of the division method. Our results agree with Maple’s gcd command. Our procedure works with a negative value. [GCD3.mw] Figure 9.9 shows a recursive implementation of the division method. Note the use of return to terminate an otherwise endless loop. The remember option causes Maple to save results in a table so that on the ‘home trip’ values are already known and do not need to be recalculated.

9.5 Further procedure examples [Prog5.mw] This worksheet (figure 9.10) demonstrates the use of the error option. The statement uses the text Empty list, and this is what gets displayed. Output (2) shows the procedure returning a symbolic result. 9-5

Maple

Figure 9.4. Two procedures with loops.

Figure 9.5. Demonstration of using return.

9-6

Maple

Figure 9.6. Euclid’s algorithms.

Figure 9.7. Euclid’s subtraction method.

9-7

Maple

Figure 9.8. Euclid’s division method.

Figure 9.9. A recursive method.

[Prog6.mw] The IsHere procedure (figure 9.11) tests to see if something is a member of a given list or a set. While this merely duplicates Maple’s member command, it does illustrate several programming features. In the procedure heading, the permitted types for parameters a and L are specified as anything and

9-8

Maple

Figure 9.10. Finding the average of a list’s elements.

Figure 9.11. Another example of return.

9-9

Maple

Figure 9.12. Procedure returning two values.

either list or set, respectively. It is instructive to look again at the use of return: if a is found in L, the return kicks in giving IsHere the return value of true and terminating the procedure. Should it not be found, then the last statement in the procedure is executed (figure 9.11). [Prog7.mw] The cylinder procedure (figure 9.12) is an example of a procedure that returns two values. Both values have been rounded to 4 significant digits with evalf[4].

9.6 Fourier expansion [Square.mw] The Fourier expansion of a square wave is given by: n

square = a 0 +

∑ ak cos(kx) + bk sin(kx) k=1

1 where: a 0 = π

∫0

π

d x , ak =

1 π

∫0

π

cos(kx )dx, b 0 =

1 π

∫0

π

sin(kx )dx

Whereas in previous examples we have used a loop to add a series of expressions, here we use the add command (use ?add for complete details) within a procedure to generate the expansion—figure 9.13. The expansion was terminated after 10 terms. Note the use of the piecewise command. The interested reader may wish also to look at the worksheet Sawtooth.mw.

9.7 Common errors in procedures A common error is missing the colon or semicolon at the end of an instruction5. If a colon or semicolon is missed inside the program, Maple would treat the line as 5 At this stage it does not matter if you use a colon or a semicolon, other than after end proc where a colon suppresses the echoing of the procedure and a semicolon (or nothing) causes Maple to echo the code.

9-10

Maple

Figure 9.13. Fourier expansion.

incomplete and continue reading the next line. Consequently, an error message may point to the line below. The author’s rules-of-thumb are: (1) no punctuation at the end of the procedure header, (2) no punctuation after then in if…then or do in for…do or while…do, (3) semicolons after all other statements, (4) colon after end proc to prevent echoing of code.

9-11

Maple

Figure 9.14. How Maple treats punctuation.

Figure 9.14 is instructive; compare the input and output code. Maple has replaced colons by semicolons (as in local i:) or has removed unnecessary ones in several places. Had there been more than one statement in the if…end if structure, separation by semicolons would have been necessary.

9-12

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 10 Working with external files

In this chapter we briefly look at working with external files. Maple can export data to a wide variety of file types including MATLAB files, comma and tab delimited, etc, but we will concentrate on text (*.TXT) and Excel (*.XLSX) files. For convenience our files will exist in a folder called Maple on a USB drive acting as the D drive. To use a file in a folder called Maple in your Documents folder use something like this as the full filename: ‘C:/Users/ItsMe/Documents/Maple/Data.txt’ where ItsMe is to be replaced by your Windows user name1.

10.1 Export and import a matrix [File1.mw] In this worksheet (figure 10.1) a matrix is exported to a text file and then imported back. With the ExportMatrix and ImportMatrix commands there is no need to use explicit open and close commands. The insert in the figure shows the file opened in Notepad. The 8 in output (1) records the number of bytes written to the file.

10.2 Using fprintf Table 10.1 (below) lists the elements that apply to fprintf and to printf. [File2.mw] The worksheet (figure 10.2) demonstrates the use of the commands fopen, fprintd, and fclose. Had the fopen statement ended with a semicolon the output would have been a simple integer corresponding to the file number (here it would be zero); this number is called the file ID. The file can be referenced by its ID and subsequent fprintf and fclose commands. The fopen syntax is fopen(full_ file_name, mode, type). Here the mode is WRITE; there was no need to

1

Older versions of Maple required a double backslash: C://Users//ItsMe//Documents//Maple//Data.txt.

doi:10.1088/2053-2571/ab0bb3ch10

10-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 10.1. Write and read a matrix to/from txt file.

Table 10.1. Data elements specifications in fprint and printf.

Element %a %ka %d %kd %e %ke %k.qe %f %kf %k.qf /n %s %ks

Data type Algebraic expression. Algebraic expression displayed using k characters. Integer. Integer displayed using k characters2. Floating-point number displayed in scientific notation with 6 digits after the decimal point in the mantissa. Floating-point number displayed in scientific notation using k characters, with 6 digits after the decimal point in the mantissa. Floating-point number displayed in scientific notation using k characters, with q digits after the decimal point in the mantissa. Floating-point number displayed in decimal format with 6 digits after the decimal point. Floating-point number displayed in decimal format using k characters, with 6 digits after the decimal point. Floating-point number displayed in decimal format using k characters, with q digits after the decimal point. Beginning of a new line. String. String displayed using k characters.

10-2

Maple

Figure 10.2. Write data to a text file.

specify TXT as the file type since that is the default. To the right of the figure we see the file opened in Notepad.

10.3 Using readdata [File3.mw] The worksheet (figure 10.3) reads numeric data from a text file. The syntax for the readdata command is readdata(filename, data_type, number of columns); the data type can be integer or float. The data from the file is returned as a Maple list. Conversion to a matrix is the simplest way to plot the obtained data.

10.4 Read data from an Excel file [Excel1.mw] The worksheet in figure 10.4 demonstrates how to import data from an Excel workbook. Figure 10.5 shows the two worksheets of the file from which data will be imported. The package ExcelTools is required to use its Import, Export and WorkbookData commands. The last command informs us of the name of the worksheets in the workbook and lists all the named cells. Output (2) shows the result of an Import statement; this command returns data in a 2D array with starting indices of 1. Output (3) demonstrates some math that can be done with this data. The Import command’s third parameter can be either a cell or range reference using the Excel RC format, or it can be the Excel name given to a cell or range of cells. The latter is illustrated in output (4). In the last execution block the range of cells named Data is imported: note that, although Excel is less fussy about capitalization, Maple requires the capital D here since that is how the cell was named. Then a loop is used to sum3 the cells that make up the Data range. This gives

3

The Maple code uses a variable named summ because the word sum is reserved.

10-3

Maple

Figure 10.3. Example of readdata.

10-4

Maple

Figure 10.4. Importing data from an Excel workbook.

10-5

Maple

Figure 10.5. Excel workbook used with Import.

us the same result as Excel’s SUM formula; at other times results could differ slightly as Excel uses 15 place precision and Maple uses 10 (by default).

10.5 Write data to an Excel worksheet [Excel2.mw] This worksheet (figure 10.6) exports data to an Excel workbook. If the book does not exist, the Export command will generate it; the first WorkbookData command returns an error telling us the file does not exist but the second one (after Export has been invoked) gives data that clearly indicates that the file exists. The data that may be exported must be what Maple calls an R-table; this restricts the data to a vector (vertical or horizontal), a matrix, or a one- or two-dimensional array. Figure 10.7 shows the worksheet resulting from the export command in the Maple worksheet. Note that the cell reference can be in RC format or a named cell4; Maple lets us code the RC cell reference in upper or lowercase.

10.6 The Task Assistant Import [TaskAssist.mw] This tool may be used to import from text files or Excel files. Figures 10.8 and 10.9 summarize the steps and show the results. The reader is encouraged to experiment with this method.

4

Of course, we cannot use a cell name as the third parameter when the file is non-existent!

10-6

Maple

Figure 10.6. Exporting data to an Excel workbook.

Figure 10.7. The Excel worksheet that is produced.

10-7

Maple

Figure 10.8. Task Assistant Import.

10-8

Maple

Figure 10.9. Result for Task Assistant.

Figure 10.10. Copy and paste from Excel.

10.7 Copy and paste For simple data structures it is easy to copy from Excel to Maple. To the right in figure 10.10 we have part of an Excel worksheet with two rectangular blocks of data and a cell with a formula. To the left is a Maple worksheet. The user copied B2:D4 in Excel, moved to the Maple worksheet, typed a:=, and then pasted with the CTRL +V shortcut to get the matrix shown. Next the user copied B7:D7, typed b:= in the Maple worksheet, and performed the paste to get a row vector. Had they copied a column of numbers, the result would have been a column vector. The Excel formula in B9 generates a concatenated list of numbers. The user copied B9; in Maple they typed c:=, performed the paste, then added the square parentheses to get a list. The alternative would be to use c:=convert(b,list). The reverse procedure (copy from Maple, paste to Excel) is unsatisfactory.

10-9

IOP Concise Physics

Maple A primer Bernard V Liengme

Chapter 11 Regression and statistics

In this chapter we briefly look at regression (curve fitting) and statistics.

11.1 Linear regression We have data relating the electrical resistance of a device at various temperatures. We wish to fit the data to a linear function, finding both the slope and the intercept of the line of best fit in the least-squares model. For a simple problem like this we have the choice of using the CurveFit or the Statistics package. [LinearRegr1.mw] This worksheet (figure 11.1) uses the LeastSquares command from the CurveFit package. The syntax is LeastSquares(independent values, dependent values, variable name). In this worksheet vectors are used to hold the data, but one may use lists or arrays. In another form, one can use a matrix to hold the xy data—see Maple’s help. The command provides us with the equation of the line of best fit as r = 105.63 + 0.47t. In a later example the command is used to fit quadratic data. Note how few commands are contained in the package. [LinearRegr2.mw] The LinearFit command from the Statistics package generates the same equation but with the option summarize it provides more information, as seen in figure 11.2. The reader is encouraged to experiment with the option summarize = embed. The first parameter for this command (here [1, t]) is a vector specifying the fit is to use a function in the form a + bt, where a and b are the fit coefficients that we seek. In output (2) the vector is [t, 1] and the resulting equation is in the form r = 0.47t + 105.63. The worksheet also shows how to get a plot1 of the trend line and the raw data. [QuadRegr.mw] It should be noted that the term ‘linear fit’ does not apply just to the straight line (y = a + bx). It means that the function to be fitted is in the form F(x) = a1 *f1(x) + a2 *f2(x) … where fi(x) is a simple or complex function of x. Other 1

Since plot2 has the label information, it must appear first in the display command.

doi:10.1088/2053-2571/ab0bb3ch11

11-1

ª Morgan & Claypool Publishers 2019

Maple

Figure 11.1. The LeastSquares command.

authors2 state that F is linear when the partial derivatives of each coefficient are not functions of other coefficients. Both the LeastSquares and the LinearFit command can be used to fit polynomial data as shown in figure 11.3 where they are used to fit data to a quadratic. In this worksheet rather than load an entire package, only the command needed is loaded with the form package:-command. The interested reader may also wish to use Maple’s Help to learn about the PolynomialInterpolation command—see worksheet PolyInter.mw.

11.2 Non-linear regression In this section the commands NonLinearFit and Fit from the Statistics package are demonstrated. [NonLinReg1.mw] This worksheet (figure 11.4) uses the NonlinearFit command to fit some data to the equation y = a + b·exp(cx). [NonLinRegr2.mw] The scenario for this worksheet is: An engineer has data for a liquid giving its vapor pressure at various temperatures. The engineer wishes to fit b this data to the equation Log10(P ) = a + + c log10(T ) + dT 2 . The vapor pressure T data is converted to the logarithmic form with a simple loop—see figure 11.5. Note the definition of LogP as an array; while the NonLinearFit command can cope with Temp being a list, the results of the loop have to be stored in an array. In the final equation, the reader will note the Ln(T )/Ln(10) equates to Log10(T ) [NonLinReg3.mw] This worksheet (figure 11.6) uses the Fit command to fit some data to the equation y = a + b·x + c/x.

2

For example: Billo E J 2001 Excel for Chemists (New York: Wiley).

11-2

Maple

Figure 11.2. The LinearFit command.

11.3 Descriptive statistics [StatDiscrib.mw] The worksheet shown in figure 11.7 demonstrates some of the commands available to generate descriptive statistics such as mean, mode, standard deviation, etc.

11-3

Maple

Figure 11.3. Data fitted to a quadratic.

Figure 11.4. An exponential fit.

11-4

Maple

Figure 11.5. A more complicated fit.

11.4 Sample or population? When one speaks of the standard deviation it is important to state if one is working with a sample or a population.

11-5

Maple

Figure 11.6. Example of the Fit command.

11-6

Maple

Figure 11.7. Some descriptive statistics.

11-7

Maple

Figure 11.8. Standard deviations. n

∑(xi − Standard deviation of a sample: s =

x )2

i=1

(11.1)

n−1

n

∑(xi − Standard deviation of a population: σ =

i=1

x )2

(11.2)

n

[Stdev.mw] To discover which one Maple reported was problematic; the author finally found the answer in Help under variance where it is clear that Maple uses the sample formula for both variance and standard deviation. To confirm this, the worksheet in figure 11.8 computes the standard deviation using equation (11.1) above and the Maple command. The results are identical.

11.5 Hypothesis testing [OneSampleZ.mw] The task for this worksheet (figure 11.9) is to test some data to see if its mean and standard deviation are what we think they are. For this exercise, a tool in Excel was used to generate a dataset with 100 values having a normal

11-8

Maple

Figure 11.9. A one sample Z test.

distribution with a mean of 2 and a standard deviation of 1.5. The data was then copied into the Maple worksheet. The command we use is the OneSampleZTest that is available in the Student[Statistics] package. The command requests the data be tested to see if the mean is 4 and the standard deviation is 1.5. It reports that the null hypothesis (mean = 4, Stdev = 1.5) is rejected. Observe the histogram; clearly the mean is around 2 as expected! The reader should change the second parameter from 4 to 2 and observe that the test then supports the null hypothesis.

11-9

Maple

Figure 11.10. A two-sample T test.

[TwoSample.mw] The purpose here is to examine two datasets and determine if, statistically, they have the same mean—figure 11.10. In the statement TwoSampleTTest(X, Y, 0, confidence = .95), the third parameter is the difference in the means that we are testing for; to test if the means are statistically the same we use a parameter value of zero. Although X and Y clearly have different means, the test shows that the populations from which these samples were taken could have the same mean. The Statistics package is used in this worksheet; had Student[Statistics] been used there would have been no need to include the summarize parameter. [TwoSamplePaired.mw] The scenario for this worksheet is: A student had measured six resistors and recorded their values (in kΩ) as dataset X—figure

11-10

Maple

Figure 11.11. A two-sample paired test.

11.11. The resistors were then exposed to x-rays, re-measured and the data reported as dataset Y. The first resistor initially had a value of 1.46 kΩ but after irradiation it was 1.42 kΩ—this hopefully explains the meaning of paired in this exercise. The student wishes to test the hypothesis that the mean difference for the two datasets is zero; i.e. irradiation had no effect. As in the previous worksheet we use zero as the expected difference for this hypothesis. The test reports that the null hypothesis cannot be rejected.

11.6 Combinations and permutations [CombPerm.mw] This worksheet (figure 11.12) briefly looks at the following commands3: (a) binomial: computes the binomial coefficients. In output (1), we see that the coefficients of xn in the expansion of (x + a)5 are 1, 5, 10,10, 5, 1. Output (2) returns the coefficients of x2 and x4. 3

All but binomial require the combinate package to be loaded.

11-11

Maple

Figure 11.12. Combinations and permutations.

(b) choose: generates a list of possible combinations. The first parameter is either a list or a set of elements, or a number representing the number of elements to be considered. Output (3) resulting from choose with two parameters, generates the possible combination of 4 elements taken 2 at a time. With just one parameter we get the list/set of the possible combinations of 4 elements, taking 0 to n elements at a time—output (4). (c) numbcomp: counts the combinations of the elements of n taken m at a time, see output (5). If we have 4 elements in list/set and take two at a time, there are 6 possible outcomes as seen in (b) above. If we sum the number of combinations taken 0, 1, 2, 3 or 4 at a time the answer is 16.

11-12

Maple

(d) permute: is similar to choose but for permutations. See output (6). (e) numbperm: counts the permutations of the elements on n taken m at a time— output (7). With 4 elements taken 2 at a time there are 12 possible permutations, and the total number of permutations taken 0 to 4 at a time is 24. (f) randperm: returns a random permutation of the elements—output (8). Without randomize(), we would get the same result every time the worksheet was recalculated.

11-13