Maple Basics

Algebraic Computing

Computers are often thought of as being only capable of solving problems numerically. But this is a far cry from the truth. There exist many Computer Algebra Systems (CAS) available on a variety of computer systems which allow us to perform very sophisticated analytical mathematical operations. These systems originated from techniques of artificial intelligence developed over many years. Today they allow mathematicians, scientists, engineers, and financial modelists to often find analytical solutions to their “real life” problems. Furthermore, these packages offer the extra capability of evaluating expressions numerically to any desired accuracy. They are fast becoming standard tools within these professions. They can also help students to develop a better intuition for “equations” via the availability of a variety of tools, both analytical and graphical; they are thus becoming an integral part of science and engineering teaching.

Maple is such a Computer Algebra System which was developed at the University of Waterloo (Canada). It is available for a variety of personal computers (MS Windows, OS X, Linux, etc.) and Unix workstations (SUN, Linux, etc.). The student versions for OS X and MS Windows computers are very complete and capable packages which will be able to satisfy most student’s needs. We have adopted Maple as our standard “algebraic” package in this textbook.

This chapter will introduce some basic Maple concepts and syntax. This chapter forms the basis on which the applications presented in the following chapters will build.

Maple Worksheet

Maple opens with an empty worksheet. This is the canvas by means of which the user interfaces with Maple.

The first screen presented to the user is a tip-of-the-day dialog and a help panel superposed on a blank document. The tip-of-the-day message is both informative and fun to read. You can learn useful tricks about Maple by displaying various messages. Click this window closed after reading the message(s).

The help panel is toggled via the F1 key, e.g., pressing the F1 key triggers the closing and opening of the help panel. Make it disappear for now.

Maple opens a new worksheet in document style. This style is appropriate to write active documents that contain a mix of text and mathematics. We will write such documents later. It will be easier for the moment to create well defined execution groups to provide an intuitive and structured document layout.

The user directs Maple to perform tasks via commands which are typed directly at the input prompt (>). Maple also presents a menu bar which allows some basic functions to be performed at the click of a button.

Maple 14 menu bar

The Maple 14 menu bar

Bringing the cursor on top of any of the icons on the menu bar triggers Maple to display a short explanation of the function of the targeted icon. For instance, the first icon on the left creates a new worksheet, the second opens an existing worksheet (with an ensuing dialog), the third saves the worksheet, the forth triggers printing of the worksheet and so on, The functions of the first few icons are pretty much universal among different applications. Others, like the T option which triggers the text mode (as opposed to the Math mode), are particular to Maple.

The menu bar on the Linux, PC and Macintosh platforms remains active through each Maple session, and can also facilitate the file manipulations, as well as the access to the Maple help functions. The file pull-down menus illustrated below show customary and easy to understand functions.

Maple 14 file menu

The Maple 14 file menu

Let us create an execution group. To do so, find the command execution group in the insert menu bar, and click on the after cursor option (alternatively, you can use the Insert-execution-group menu icon menu icon, or the hotkey Ctrl+j).

Each execution group is characterized by an input prompt > followed by one or many Maple commands. These commands are input by the user and displayed by Maple in a variety of formats, usually 2D Math or Maple Input. You can toggle the current format with the F5 key or via the Text and Math buttons at the top of the document menu bar.

Maple 14 document menu bar

The Maple 14 document menu bar

Maple's assorted input and output formats

Equivalent input in both 2D Math and Maple Input mode. We also use the interface command to specify output formatting.

A Maple worksheet consists of a series of commands, divided among execution groups, optionally separated by text. Each command is an operator form terminated by a semicolon (;). The commands are typed at the input prompt (>). The enter key (regular return key on the keyboard or the key at the bottom right on the numeric keypad) triggers the transmission of the command (or group of commands) under a single prompt to the Maple compute engine. The results are then written out to an output region on the worksheet. Note that commands are never re-run by Maple, unless they are entered again. Shift+Return allows to insert a new prompt from within the same execution group; this will become essential later. You can identify execution groups by the bracket ([) in the left margin stretching to contain a region of the document. If multiple commands are contained in a single execution group, they will be evaluated as a block.

Between (or within) execution groups, you can insert text, which is ignored by the Maple engine. Text blocks can be entered at the prompt via the text mode icon (Insert-text-group menu icon), while Ctrl-T switches to text input within the current execution group. This is useful to write titles and comments to better document the work.

Interspered text and execution groups

Interspersed text and execution groups, with some text sections inside the execution groups

You can also split and join execution groups after the fact via the Edit→Split or Join menu.

Simple Algebra

Maple knows how to do simple arithmetic; it knows how to add (+), subtract (-), multiply (*), divide (/), and exponentiate (^). It understands and uses parenthesis (( and )) following the usual algebraic rules.

All Maple lines or commands must be terminated by a semicolon (;). Maple is a free-format language with no imposed command line length, and where spaces do not matter. Use spaces to make the typing easier to read and interprept. A semicolon implies the end of a command block for the compute engine. In general the syntax of Maple commands is:

command ( argument list );

Maple always defaults to algebraic mode. If there are numbers in the expression, Maple defaults to integer arithmetic, i.e., presents the results in rational fractions. The command evalf forces Maple to evaluate an expression in floating point via the syntax:

evalf(exp, acc);

where exp is any valid Maple expression and acc is the (optional) number of digits with which to do arithmetic. Maple defaults to 10 digits accuracy. In this sense, Maple constitutes an excellent calculator. Maple also defaults to floating point arithmetic if it detects floating point numbers in an expression. For more details, see the Maple help on the evalf command (i.e., by typing ?evalf at the prompt).

Examples of Maple evaluation

Examples of Maple evaluation

Maple also knows how to do algebra. In particular, the commands expand(exp), factor(exp), and simplify(exp) expand, factor, and simplify any algebraic expression. These commands are particularly useful in manipulating polynomials.

Recall that the results in this section can also be displayed in 2D math notation.

Help

Help is always available in Maple. First, there is the Help menu from the menu bar. This option provides help under the sub categories Table of Contents, Search, etc.. It is useful to browse some of the topics described in these help options when studying a new topic.

The help panels for individual keyword are also available from the worksheet via a ? followed by the keyword at the prompt. For instance, help on the help keyword (?help at the prompt) opens the following window:

Maple help window

Maple help window

Help on any particular command is available via ?command. For instance, try ?evalf, ?expand, ?factor, and ?simplify to learn more about about the commands we used so far.

Note that most help panels have examples which can be copied and pasted in the active worksheet.

Built-in Functions

Maple comes with a very large number of built-in functions. The help command ?inifunction provides a list of functions initially-known to Maple. This list is impressive; we will only use a few of these functions in this electronic textbook. All Maple functions are called via the syntax:

function_name(arg)

where function_name is the name of the function, and arg is a single variable or many variables which are the argument(s) for the function.

In particular, we will use the trigonometric functions, i.e., sine, cosine and tangent. These are called by sin(arg), cos(arg), and tan(arg). The argument to these functions is an angle in radians (expressing angles in radians is standard for most computer languages). Lets convince ourselves that Maple knows trigonometry by executing the following commands:

Basic trigonometry functions

Basic trigonometry functions

Note that the value of Pi (case sensative) is known to Maple.

?initialconstants

will list the initially known constants in Maple.

evalf(Pi,15)

will echo the value of Pi using 15 digits arithmetics. You should use the abstract variable Pi (not a numerical value) in carrying out calculations to minimize rounding errors and take full advantage of Maple’s symbolic manipulations.

Maple not only knows how to evaluate the trigonometric functions, but it also knows trigonometric relations!

Basic trigonometry identities

Basic trigonometry identities

Note that gamma, phi, and theta translate into the proper Greek letters in the Maple output.

Basic Plotting

The best intuition about mathematical functions is gained by plotting. Maple provides very powerful tools to accomplish this task, for simple x-y all the way to quite sophisticated 3-D plots.

The syntax for plotting is quite simple and intuitive. For instance, an x-y plot is obtained via the basic syntax:

plot(function, range);

or:

plot({function_1, function_2}, range);

or:

plot([function_1, function_2], range);

The range is specified by the sytax:

variable = min..max

The plot defaults to a range {-10,10} if no range is specified. The {,} or [,] notation is used to plot more than one function. The {,} generates a set out of its arguments while the [,] generates a list. See ?set for help and examples. For more examples, download the plotting examples worksheet.

Exponential and gaussian functions

An interesting function which we will need later is the exponential function exp(arg), the inverse of the natural logarithm.

Exponential and gaussian functions

Exponential and gaussian functions

Another important function is the gaussian (or bell shape) function. It is important in many fields and often appears in statistical applications. It is a simple exponential with a quadratic argument that produces a very characteristic bell shape.

Variable Assignment

Maple can remember “things”. That is, variables can be assigned values. These values can be anything: integers, floating point numbers, strings, even plots. The syntax is:

variable := value;

where the assignment operator := must be typed with no spaces (= is reserved for defining equations, as we’ll see later). For instance, the following commands assign various values to the indicated variables:

Variable assignment

Variable assignment

The restart command starts the Maple compute engine anew. Doing this unassigns all user defined variables.

The value of a variable is recalled by simply using the name of the variable in any valid Maple expressions; a variable on a line all by itself forces echoing the value of the variable.

Using the right name for variables helps considerably to understand the logic of the work. For instance m:=5 and my_name:="Vallières" seem fine, while my_name:=5 is highly non-intuitive.

User Defined Functions

The power of Maple really becomes apparent when defining new functions. Functions are best understood in terms of creating a relation between an independent variable and a mathematical expression involving the independent variable, i.e., given the value of the independent variable, it provides a recipe to compute the function. This relation is called a map in mathematics. The Maple syntax to accomplish this task is that of an assignment of a map to a variable, here the function name:

function_name := map;

A map is defined in terms of specifying the relation between an independent variable and the function via a simple “arrow” (“minus” sign followed by the “greater” sign with no space):

independent_variable -> mathematical_function

The function is evaluated by using its name with the value (algebraic or numerical) of its argument in parenthesis. This is the same syntax as for the intrinsic built-in functions. They may also include calls to other functions.

Function definition

Function definition

Functions provide relations between dependent variables and independent variables; they are therefore intuitively understood by plotting these relations. Function evaluation can be used as arguments of Maple operators.

Another syntax:

unapply(expression, variable)

can be used to define functions. This syntax must be used to define functions in terms of Maple generated expressions (see ?unapply). The user might prefer to exclusively use the unapply command instead of the “arrow” notation for consistency; it is in most cases a matter of choice since the two syntaxes are mostly equivalent. The unapply notation will always work, with unapply producing early binding and the “arrow” notation producing late binding.

Function definition using unapply

Function definition using unapply

Functions can be made out of other intrinsic or user-defined functions. These more complicated functions are often needed by modelers in various fields to better describe different systems.

Point on rim of wheel

Lets consider a point on the rim of a wheel. Its x and y coordinates depend on the angle φ the radius makes with the x-axis as shown in the adjacent graph.

Parameterized point on the rim of a wheel

The angle φ is itself a function of time as the wheel turns. In fact, if the wheel speeds up, the φ might increase as the square of the time. The constant of proportionality is called the angular acceleration by physicists. Therefore:

φ = ½αt²

This translates into the following Maple worksheet:

Point on the rim of a wheel worksheet

Point on the rim of a wheel worksheet

Note that α must be specified numerically for the plot.

This application begs us to graph the trajectory of the point on the wheel and to animate it. This will be adressed in Parametric Plots and Animations.

A bumpy ride

Amazing shapes can be reproduced via superpositions of known functions. This is often used in modeling complicated functional dependencies.

Our friendly financial analyst is looking at the price of a service rendered by his firm. The price has had a bumpy ride over the last 5 months. Here is how he represents the data as a superposition of gaussian functions.

Modeling price with a superposition of gaussians

Modeling price with a superposition of gaussians

He first defines term for drawing a single gaussian (Exponential and gaussian functions) that depends on the time t and on an index k. The function α(k) defines the width of the bell shape. The center of the bell is shifted by displacing the argument, i.e., t-k; this centers the Gaussian on the value of t = k. This is illustrated in the plot of the individual terms. Note the bells centered at 1, 2, and 3 and with increasingly narrow shapes. The price function is the superposition (sum) of three terms with k as 1, 2, and 3. Note the shape of the price(t) function that results.

The bumpy ride made easier (sum command)

Maple can sum terms automatically via the sum(expression,range) command. In this command the expression is the term to sum over. The range argument specifies the range over which the index characterizing the expression is to be summed over. The following worksheet exemplifies the sum command and its siblings Sum and add.

The sum command in action

The sum command in action

The sum command makes writing the Bumpy Ride function easier to code in Maple. It avoids spelling out the possibly tedious list of terms in the sum. Sum is the inert form of sum; it is not expanded into a list of terms. The add command computes explicit sums. For numerical calculation, add can be more efficient than sum (which attempts to compute a closed-form analytic expression for the sum).

Parametric Plots and Animations

In this section we’ll use the Point on rim of wheel to demonstrate some more sophisticates plotting techniques.

Parametric plots

The trajectory of the point on the rim of a wheel that is speeding up is illustrated below via the Maple parametric plot command. The x- and y-coordinates of the point are given by the x(t) and y(t) functions that depend (parametrically) on time. The trajectory is generated by plotting y(t) versus x(t). The syntax is discussed in the help panel generated with ?plot[parametric].

In this example, the command generates values of the parameter t in the range t=0..3.2. The positions of the point (values of x(t) and y(t)) are automatically generated and displayed through the graph. The scaling=CONSTRAINED option in the plot command is to invoke the 1:1 scaling—to make the trajectory appear as a circle, which it is. The view option sets a viewing window.

The point on the rim starts from rest on the positive side of x-axis. As time passes, the point rotates counter-clockwise. The dots on the figure become further apart (same time interval between the dots) since the speed of rotation of the wheel increases (linearly) with time.

Parametric point on the rim of a wheel

Parametric point on the rim of a wheel

Animation

Maple is an exceptionaly versatile package for plotting functions. It is equally capable of producing animations.

The command animate in the plots library allows you to animate a variety of plot commands. The syntax is:

animate(plot_command, [arguments], parameter=range);

This animates the command plot_command(arguments) over the specified range of the parameter. For instance, the worksheet below animates a gaussian curve over a range of widths. The statement:

plot( gaussian(x), x=-3..3);

would plot the gaussian function of standard width. gaussian(alpha*x) are gaussian functions of width controlled by the parameter alpha. Therefore, the animate statement makes a “movie” based on gaussians of different width in each frame.

A gaussian of animated width

A gaussian of animated width

Try this for yourself by downloading gaussian-animation.mw. Note that clicking the graph displays the movie control buttons (stop, play, etc.) in the top bar.

Point on an Accelerating Wheel

The trajectory of the point on the rim of an accelerating wheel is illustrated below via an animation created by Maple. The idea is to animate the trajectory based on an increasing time of the last point on the trajectory (leaving behind a trail of already-visited points).

Animated trail of a point on the rim of a wheel

Animated trail of a point on the rim of a wheel

Try this for yourself by downloading wheel-animation.mw.

Animation via a Sequence of Plots

The animation above is easy, but not really the best. It would be more natural to see the point on the rim of a wheel itself move along the trajectory. This is illustrated below via an animation created by Maple. This application is much more intricate than a novice is normally expected to know. Yet it is reassuring and satisfying to realize that Maple is a very capable package, able to render very sophisticated graphics.

The basic idea is to create a function of t which is a plot of a single point corresponding to the position of the point on the rim at time t. Then a series of plots is generated via seq(exp,range). These are displayed via the display command, in which the parameter insequence is set to true so as to display the plots in sequence.

Animated point on the rim of a wheel

Animated point on the rim of a wheel

Note that seq generates a sequence of integers, which are transformed in a reasonable time range by multiplying by a factor 0.05.

Try this for yourself by downloading wheel-animation.mw.

Animated GIF

The animated graphic can be transferred into an animated GIF file via specifying the output device to be a GIF file for the display command. The command plotsetup is used for this purpose.

Animated GIF creation for a point on the rim of a wheel

Animated GIF creation for a point on the rim of a wheel

The result is a GIF file which can be viewed via a browser.

Animated GIF for a point on the rim of a wheel

Animated GIF for a point on the rim of a wheel

The commands used here are quite complicated; they accept many more options than those shown. This section is meant to be complemented by the help files from Maple for the serious reader who needs to use these more sophisticated graphic capabilities.

Functions of Two Variables

Definition and use

As we touched on back in A bumpy ride, you can define functions of two variables with either of:

name := (var1, var2) -> expression;
name := unapply(expression, var1, var2);

In either cases, name is the name of the function, var1 and var2 are the independent variables, and expression defines the map. The function is used via:

name(var_a, var_b)

The associations var_avar1 and var_bvar_2 are though the positions of the variables in the definition and call.

Surface plots

A function of two independent variables, f(x,y), defines a surface. Given numerical values for x and y, the function f(x,y) maps these values of x and y into a number. This can be done on an x-y grid from which Maple can draw the surface. The command:

plot3d(f(x,y), x=range_x, y=range_y, options)

plots the surface specifiied by f(x,y) in the x-y domain specified by range_x and range_y using a default 25x25 grid.

Note that Maple allows full control over the graph and the observation point. A mouse click on the graph enables options to appear in the top bar. You should explore the variaty of textures and axes that are available. You should also grab the surface and rotate it. This provides an amazing tool to study any surface by allowing you to inspect the surface from any angle.

The command is also capable to display multiple surfaces at once. The following worksheet shows how easy it is to display a cone intercepted by a plane. Note how simple the syntax is and how it contitutes a simple generalization of what we saw for the plot command.

The command also accepts many options. For example, the option grid=[m,n] where m and n are positive integers, specifies that the plot is to be constructed on an m by n grid at equally spaced points in the x and y ranges respectively. By default, a 25 by 25 grid is used and 625 points are generated. Other options include specification of alternate coordinate systems and rendering styles. For more information, see ?plot3d,options.

Analytical manipulations

Maple allows full analytical manipulations with functions of multi variables. For instance the following worksheet illustrates how the axial symmetry property of a cone can be used in its definition. Functions of one and two variables are used as arguments of each other.

Multi-variable functions

Maple allows the definition and use of multi-variable functions. This is exemplified in the next worksheet with a function of three variables.

The plotting of such functions can be tricky or impossible (we live in 3D). One way to “see” functions of many variables is via slices through the data. For instance f(x,y,0) selects a slice of the function in the plane z=0. The command plot3d can be used in contour mode, in a specific x-y domain, with the color display being defined by the function f(x,y,0) itself. To see the contour plot, the constant function 0 is plotted and viewd from an observation point above the plane, orientation=[-90,0]. The color and contour values are therefore plotted in this plane (z=0) with no distortion. The x-y grid is refined by specifying grid=[250,250] instead of the default 25x25 size. Reading the help ?plot3d,options will help in understanding this complicated plot!

Lists, Sets, Sequences and Maps

A list is a sequence of expressions enclosed in square brackets. The ordering of the expressions is the ordering of the items in [a,b,c].

A set is a sequence of distinct expressions enclosed in braces, representing a set in the mathematical sense. The items in {a,b,c} are ordered and duplications are eliminated. It is not a good idea to make any assumptions about the ordering of items in a set. If you care about ordering, use a list.

The Maple command seq(expression,variable=range) generates a sequence of items according to the pattern implied in the expression, e.g., i^2 or f(i). The generated sequence can be assigned to a variable, in which case the various items in the sequence can be extracted via an array notation, e.g., name[i] to extract the ith items.

A sequence generated by seq can be placed in [] or {} to form either a list or a set. This list or set can be assigned to a variable.

The Maple command map(function,list) distributes the application of a function f(x) over a list or a set of arguments.

The seq command can be very handy in generating plots of multiple functions characterized by an index.

The seq command can also help generating sequences of plots as shown below. The plot structures can be stored in a variable and displayed via the command plots[display]. The latter is the display command in the plots library. The statement with(plots) loads this library in memory. If the statement is terminated with ; this command will display the content of the library; terminating the statement with : will turn this listing off.

The following worksheet illustrates a graph made out of straight lines joining points in a plane. In this case the plot command accepts a list of points, each one specified by a list of two items, the x- and y-coordinates of each point. The seq command can help generating such a list of points.

Excercises

  1. Define and plot the following functions:

    f1(x) = exp( - 0.3 x 2 ) sin(x)
    f2(x) = sin(x) cos(x)
    f3(x) = sin(x) + cos(x)
    f4(x) = sin(x) + sin(2x)
  2. Plot the functions f1(x) through f4(x) simultaneously in a single graph.

  3. Find by inspection the intercepts of the functions f1(x) and f2(x) in the interval x=[-p,+p].

  4. Define a function of two variables fa(x) = exp(-ax²) via the Maple syntax:

    f := (alpha,x) -> …

    Plot f(a,x) for a=0.5,1.0,1.5,2.0 simultaneously in a single graph.