M. Majewski Getting Started with MuPAD
Springer Berlin Heidelberg New York Hong Kong London Milan Paris Tokyo
Mirosl...
122 downloads
2393 Views
33MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
M. Majewski Getting Started with MuPAD
Springer Berlin Heidelberg New York Hong Kong London Milan Paris Tokyo
Miroslaw Majewski
Getting Started with MuPAD
ABC
Miroslaw Majewski College of Information Systems Zayed University P.O. Box 4783, Abu Dhabi United Arab Emirates http://www.mupad.com/majewski/
Library of Congress Control Number: 2005932084 ISBN-10 3-540-28635-7 Springer Berlin Heidelberg New York ISBN-13 978-3-540-28635-6 Springer Berlin Heidelberg New York This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilm or in any other way, and storage in data banks. Duplication of this publication or parts thereof is permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and permission for use must always be obtained from Springer. Violations are liable for prosecution under the German Copyright Law. Springer is a part of Springer Science+Business Media springeronline.com c Springer-Verlag Berlin Heidelberg 2005 Printed in The Netherlands The use of general descriptive names, registered names, trademarks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. R Typesetting by the author using Scientific Workplace from MacKichan Software, Inc. Cover graphics by the author using Strata 3D and the background image from online NASA collection. Cover design: design & production GmbH, Heidelberg Printed on acid-free paper
SPIN: 11547808
40/TechBooks
543210
Table of contents
1 Introduction to MuPAD ................................................................... 1 1.1 A brief history of MuPAD ........................................................................1 1.2 MuPAD as a calculator ........................................................................... 2 1.3 Solving equations ................................................................................... 6 1.4 Transforming mathematical expressions .............................................. 9 1.5 Differentiation and integration ............................................................ 12 1.6 Declaring functions ...............................................................................14 1.7 Graphs of functions in one variable ..................................................... 18 1.8 Graphs of functions of two variables ................................................... 19 1.9 Selected mathematical structures in MuPAD ..................................... 20 1.10 Looking for help ................................................................................. 24 1.11 Using libraries ..................................................................................... 26 1.12 Tracing basic errors ............................................................................ 28 2 Mathematical graphics with MuPAD .............................................33 2.1 Secrets of the Virtual Camera .............................................................. 33 2.2 The structure of MuPAD graphs ..........................................................41 2.3 The gallery of mathematical plots ........................................................41 2.3.1 Function2d ................................................................................. 44 2.3.2 Curve2d ...................................................................................... 46 2.3.3 Polar coordinates ....................................................................... 47 2.3.4 Implicit2d ...................................................................................49 2.3.5 Function3d ................................................................................. 50 2.3.6 Surfaces ...................................................................................... 54 2.3.7 Implicit3d ................................................................................... 55 2.3.8 Spherical coordinates ................................................................ 58 2.3.9 Cylindrical coordinates ..............................................................60 2.3.10 Curve3d and Tube ....................................................................63 2.4 Plotting geometry models ....................................................................66 2.4.1 Points, lines and polygons ..........................................................67 2.4.2 Solids in MuPAD ........................................................................ 73 2.5 Turtle graphics and L-systems .............................................................77 2.5.1 A brief introduction to turtle graphics .......................................78 2.5.2 Lindenmayer systems ................................................................ 83 2.6 Animation step-by-step ....................................................................... 89 3 Introduction to calculus of one variable ........................................95 2.1 Declaring functions of one variable ..................................................... 95 3.2 How does MuPAD plot graphs of functions? .....................................101 3.3 Limits ..................................................................................................105 3.4 The derivative ..................................................................................... 110 3.5 Curve-sketching with MuPAD ............................................................114 3.6 Taylor polynomials ............................................................................ 120 3.7 Integration with MuPAD ....................................................................123 3.8 Numerical integration ........................................................................ 127
VI
Getting started with MuPAD 3.9 Solving differential equations ............................................................ 132
4 Multivariable calculus ................................................................. 135 4.1 Functions of several variables ............................................................ 135 4.2 Visualizing functions of several variables ......................................... 138 4.3 Limits of functions of several variables ............................................. 144 4.4 Partial differentiation ........................................................................ 148 4.5 Vector fields ........................................................................................ 151 4.6 Multiple integrals with MuPAD .........................................................154 4.7 Visualizing and calculating volumes ................................................. 160 5 Algebra with MuPAD ................................................................... 165 5.1 Numbers and domains ....................................................................... 165 5.2 Complex numbers and quaternions .................................................. 170 5.3 Polynomials ........................................................................................ 176 5.4 Systems of linear equations ............................................................... 179 5.5 Declarations of matrices .................................................................... 184 5.6 Visualization of matrices ................................................................... 188 5.7 Operations on matrices ...................................................................... 189 6 Data visualization and elementary statistics ................................195 6.1 Data formats ....................................................................................... 196 6.2 Plotting tabulated data ...................................................................... 201 6.3 Frequency distributions .................................................................... 209 6.4 Measures of central tendency ............................................................ 219 6.5 Standard deviation .............................................................................224 6.6 Correlation and regression ................................................................226 7 A brief introduction to programming ..........................................229 7.1 Variables again ................................................................................... 230 7.2 Procedures ..........................................................................................234 7.3 Getting organized ...............................................................................238 7.4 Creating user libraries ....................................................................... 239 7.5 Control structures ...............................................................................241 7.5.1 Logical conditions .....................................................................242 7.5.2 Making decisions ......................................................................243 7.5.3 Iterations .................................................................................. 247 7.5.4 Sometimes iterations and conditions do not work ................. 254 7.6 Recursion ........................................................................................... 256 8. Index ......................................................................................... 261
Preface No book is born in a vacuum. There must always be somebody who needs the book, somebody who will read and use it, and somebody who will write it. I walked with the idea of this book for a long time. However, its final concept came into reality during my lectures, in February 2005, at the Universiti Malaysia Sabah in Borneo. I realized that my students needed a bit more than just my lectures. They needed a text that they could follow during lab sessions or after classes so they could learn at any time, at their own pace. Therefore, I decided to write a small book with just a few chapters covering the different areas of applying the Computer Algebra System called MuPAD in different areas of mathematics. I intended each chapter to be short enough to be covered in a reasonably short time, about 2 to 4 hours. Another important objective was to have each chapter completely independent of the others, so that the readers could easily select and read the chapters that they needed the most, without being forced to read the whole book. There was one obstacle for such a concept—the large number of graphics I used to visualize mathematics. Therefore, I finally decided to write a separate chapter covering the major concepts of MuPAD graphics. The graphics chapter, together with the introductory chapter, forms the base for all the remaining chapters. Therefore, chapters 1 and 2 should be read first and foremost, but the remaining chapters can be read in any order. Allow me to mention what you will find in this book. Chapter 1 is the introductory chapter, and it covers some very basic information about MuPAD. You should read this chapter if you do not know anything about MuPAD. The second chapter contains a reasonably brief description of the concept of MuPAD graphics, and introduces the Virtual Camera tool and the major types of graphical objects. Chapters 3 and 4 are devoted to calculus of one variable and several variables, respectively; they require a basic knowledge of calculus. This book isn’t intended to teach mathematics; it teaches only how to apply MuPAD in mathematics. Chapter 5 is devoted to working with selected algebraic concepts with MuPAD. Chapter 6 shows how MuPAD can be used in elementary statistics and in the visualization of discrete data. Finally, chapter 7 introduces some basic programming concepts in MuPAD.
VIII
Getting started with MuPAD
The chapters in this book aren’t intended to cover specific mathematical disciplines in detail. However, the book gives the readers enough basic knowledge to start using MuPAD in several disciplines. Readers who are interested in a more detailed book on programming with MuPAD may read my MuPAD Pro Computing Essentials, which focuses on programming and using MuPAD programs in mathematics. I know that there are many other mathematical disciplines that are worth exploring with MuPAD. Perhaps one day I, or somebody else, will write the missing chapters on analytic geometry, number theory, abstract algebra, discrete mathematics, and so on. Finally, I know also that each chapter of this book could be the staring point for a new exciting textbook for a regular college or university course. For example, writing a textbook for a course on abstract algebra or discrete mathematics with MuPAD could be a very fascinating project. Therefore, this book is not only a collection of MuPAD workshops, but also can be considered as a starting point for many interesting new projects. I am very grateful to Prof. Fred Szabo and Prof. Bernard Liengme as well as to my son Jakub for proofreading and commenting on the manuscript of this book. I thank them for their wonderful support and for the time they spent helping me in this project. The first two chapters of this book were used during my lectures at Mumbai University in April 2005, and they were received with great enthusiasm by my colleagues and the participants in my lectures. The manuscript of this book, as well as all other my books, was written using Scientific Workplace, the best tool ever made for writing mathematical texts and experimenting with mathematics. I would like to thank Barry MacKichan and his excellent team for creating Scientific Workplace and for their never ending support of my work. Some additions, corrections, and the MuPAD code for this book can be found on the web site at http://majewski.mupad.com. Miroslaw Majewski Zayed University, June 2005
Introduction to MuPAD 1.1 1 A brief history of MuPAD MuPAD is a Computer Algebra System. Such systems are very unusual computer programs. They contain procedures that can be used to manipulate mathematical objects and perform operations such as solving mathematical equations, integrating functions and plotting graphs. In addition, they usually contain a programming language that allows users to define their own commands and expand the functionality of the system. These features make computer algebra systems useful for solving mathematical problems such as problems encountered in high school algebra, as well as for solving very advanced mathematical or engineering problems. Another important feature of computer algebra systems is their ability to perform symbolic operations, that is to say, operations on expressions containing symbols, and producing results in symbolic form. They can also carry out operations on numbers with high precision. They can, for example, calculate the number = to thousands of places. The beginning of MuPAD goes back to the year 1989, when Professor Benno Fuchssteiner from Paderborn University and his student Waldemar Wiwianka started a research project on handling large data generated by algorithms, used to investigate the structure of nonlinear
2
Getting started with MuPAD
systems. The first students taking part in this project were Oliver Kluge and Karsten Morisse. Their joint Master’s thesis was the first successful outcome of the project. At the same time, in the early stages of MuPAD, Gudrun Oevel, another student of Professor Fuchssteiner, developed the foundations of MuPAD graphics. Since then, MuPAD has become a major research project, carried out by researchers and students at Paderborn University. In 1997, MuPAD became a commercial product. Its producer is SciFace GmBH, a computer company in Paderborn, with Dr. Oliver Kluge as manager. It is important to mention that at Paderborn University, a strong group of researchers, called MuPAD Research Group, is continually developing and implementing new algorithms for the system and works on expanding its functionality. It is important to mention that MuPAD has a number of features that distinguish it from other computer algebra systems. These include its open concept, where all users can expand the functionality of the program by developing their own libraries, the object-oriented concept, applied to all MuPAD elements, as well as its excellent graphics and animation tools. Let us now find out how MuPAD works and what we can do with it. We will start by examining some of its features that make it resemble a super-calculator.
1.2 2 MuPAD as a calculator After launching MuPAD, a new notebook opens and a large dot appears in the left margin on the screen. This is the area, the so-called input region, where we type our commands. Let us write something there, something that we usually type when testing a new calculator, such as S 234 675 Now let us press [Enter]. MuPAD produces a result, similar to 909 The area where MuPAD displays its results is called the output region. In addition, MuPAD notebooks contain another type of region, the text region. We can insert text regions from the menu InsertInput Above or InsertInput Below. A text region is the space where we can type any text.
Chapter 1 ( Introduction to MuPAD
3
Technical comment In order to improve readability of our text, all MuPAD statements, as well as all results obtained with MuPAD, will be printed using Lucida Sans Typewriter font. In cases where the output is a mathematical formula we will use Times New Roman. Wherever convenient, we will also omit the dot from the input region.
Fig. 1.1 Text, input and output regions in MuPAD notebook MuPAD, as a calculator, can do much more than any calculator we ever used. Let us examine a few more examples. S 98765467.89765/3456.987654 28569.80637 S 234! 226701500510243392088429967939458536596181051494323328919091\ 627814531884961852861632986065166948869056073651901909595630\ 646129453387036941368576843569614678171932751596833773143536\ 624437808408963972397082885810366994838323956362463109712412\ 249963159146761732364354657983880952611680981197119192191774\ 651724175318705330712109638909510796006513526492598656929841\ 724590466979051697750368473257330343936000000000000000000000\ 00000000000000000000000000000000000
4
Getting started with MuPAD
This was quite simple. In a similar way, MuPAD can perform all other arithmetical operations with any desired accuracy. For example, a square root of 2 calculated with an accuracy of 49 digits after the decimal point, can be calculated in the following way. S DIGITS : 50: S sqrt(2.0) 1.4142135623730950488016887242096980785696718753769 The accuracy of the calculations can be very high. If needed, we can ask MuPAD to produce results with 1000 or 100, 000 places of accuracy or more. This cannot of course be done with a normal calculator used for teaching or scientific calculations. Technical comment There are two important symbols, “:” and “//”, useful for formatting MuPAD output. If we use the symbol “:” at the end of a MuPAD statement, then MuPAD produces the result, but it does not display it on the screen. If we use the symbol “//” in a MuPAD statement, then anything written to the right of it is treated as a comment and is not executed. The symbol “:”, used earlier, is what we will call an assignment operator. This operator assigns a value to a given variable or constant. In the above example, the word DIGITS denotes one of the MuPAD variables, defining the number of digits used to display decimal numbers on the screen. In our example, we requested 50 digits for displaying decimal numbers (the integer part plus a fractional part). As names for variables and constants we can use any expressions, not starting with a digit, as well as letters, digits and the underscore character. Examples of correctly formed names of variables are MySet, NumberOfData, A234, John_Brown_on_a_red_bike, and so on. Names of constants usually contain capital letters only, for example E, PI, DIGITS, CATALAN, EULER. Finally, let us note that MuPAD treats the mathematical equality symbol “" as a relation, used to compare two objects. Therefore A:123 means let A be equal 123, but A123 denotes a true or false equality.
Chapter 1 ( Introduction to MuPAD
5
Technical comment While writing MuPAD statements we should avoid using characters that do not exist in the English alphabet such as special symbols in Polish, Czech, Portuguese, etc. Usually MuPAD produces an error message if we do. However, we can use these characters in comments to the right of “//". It is worth noting that when doing arithmetic with MuPAD, the program always tries to produce exact or symbolic values, whereas decimal values, often approximate, are produced only when explicitly asked for. Therefore, if we wish to obtain results in decimal form, we must use a special float procedure, or stipulate that decimal numbers are required. This is how it might look. S 123/345
// Here we produce an exact result.
41 115 S 123.0/345 // Here we produce a decimal result. 0.35652173913043478260869565217391304347826086956522 S float(123/345) // Here is another way of getting // decimal result. 0.35652173913043478260869565217391304347826086956522 Exercise 1.1 Before we continue exploring MuPAD, it might be wise to practice a bit. Here are some exercises for you to try. 1. Calculate the decimal value of the fraction 123/456 with an accuracy of 10, 100, and 1000 places. 2. In MuPAD, the symbols PI, E denote the constants = and e respectively. Calculate = and e with an accuracy of 150 decimal digits.
For MuPAD beginners, it is important to learn how formulas are typed in a MuPAD notebook. As you would expect, we can use the arithmetical operations , ", ', / (division). Products, for example 2xy, must be written as 2*x*y. Powers, 3 2 , 5 3 , a n are written as 3^2, 5^3, a^n. Square roots 2 , 3 , a are written as sqrt(2), sqrt(3) and sqrt(a). We can use most of the well-known mathematical functions such as sin x, cos x,
6
Getting started with MuPAD
tan x, cot x. However, we must enclose the functional arguments in parenthesis, as in sin(x), cos(x), tan(x), cot(x). In order to write e x , for example, we must write exp(x) or E^x. Finally, it should be noted that several functions are used in infix form, that is, as operations between two arguments. Such functions are, for example, the two well-known integer operations mod and div. The operation mod produces the remainder of a division of one integer by another. The operation div, meanwhile, produces the result of one integer divided by another. Such operations we write in the traditional way, using parenthesis where necessary, as in (34 mod 3)(34 div 3). Note that using parenthesis may be important. For example, the two expressions (34 mod 3)(34 div 3) and 34 mod 3 34 div 3 will produce different results. This suggests that in the second formula, 334 was produced first and then the remaining operations were carried out. This may not be what we intend. Exercise 1.2 In a MuPAD notebook, type statements to declare the following variables: 1. MyRoot 2. MyFraction
x 1 2 1x"
1 x
3. Poly1 3x 3 2x 2 x 1 1 4. Fractions b 1 1 a x b
1 a 1x
5. ManyRad
1 c
1 b
1 a 1x
a a a a x
1.3 3 Solving equations Solving equations and systems of equations is one of the most important activities in mathematics. Let us examine how MuPAD solves equations. S solve(x^4 - 4*x^2 – 1 0, x)
Chapter 1 ( Introduction to MuPAD
"
5 2 , 2 " 5 ," 2 " 5 ,
7
5 1
In this example, we obtained a very elegant result. However, it may happen that MuPAD also produces strange looking results such as the next one. S solve(x^3 - 4*x^2 – 1 0, x)
RootOfX1 3 " 4 X1 2 " 1, X1 Such a result does not mean that MuPAD does not know how to solve the given equation. It often happens that the results obtained by MuPAD are too complex or too large to be displayed on a computer screen. In such cases, MuPAD uses built-in restrictions. If we do not care about exact results, we can try to obtain approximate values for our solutions. Here is how we would do this in the previous example. To produce the decimal values of our roots, first we declare the set of roots of the equation and then use the float procedure to produce roots in decimal form. S A : solve(x^3 - 4*x^2 – 1 0, x)
RootOfX2 3 " 4 X2 2 " 1, X2 S float(A) {4.060647028, - 0.03032351378 0.4953247992*i, -0.03032351378 - 0.4953247992*i} Technical comment For polynomial equations of order higher than 2, MuPAD often produces results as RootOf if their solutions contain radicals. This is because the resulting formula may be very complex and may not fit on the screen. However, we can force the program to display results in exact form. This can be done by using the solve statement, with parameters MaxDegree3 or MaxDegree4. For example, a statement like solve(x^3-4*x^2–10,x,MaxDegree3) can produce the desired formula. Technical comment MuPAD statements use specific words such as solve, float, etc. We will call such words the names of procedures or, for short, procedures. Procedures are programs that have been
8
Getting started with MuPAD written by MuPAD developers or sometimes by users of the program. Usually MuPAD users are not interested in the content of a procedure. Its name and how to use it is enough. In this book we will distinguish the names of procedures from statements using them. It is important to notice that usually there are many ways to formulate such statement. It also happens that a given procedure can be used in several contexts. For example, the procedure solve can be used to solve linear equations, quadratic equations, systems of equations and even differential equations.
Solving systems of equations with MuPAD is as simple as solving single equations. We declare a set of equations and then specify the set of variables for which we wish to obtain the solutions. Here is such an example. S solve({3*x2*y–1 0, -6*x4*y–6 0}, {x,y})
x " 13 , y 1 Here is another, slightly more complex, example. S solve({x2*y–1 0, -2*x4*y^2–2 0}, {x,y})
x 2 " 5 ,y
5 2
"
1 2
, x 2 5 ,y "
5 2
"
1 2
In these examples we solved systems of two equations, considered as a set, with respect to the set of two variables £x, y¤. Observe that exactly as in a high school textbook, we denoted the sets using curly brackets. Often we simplify the code by declaring the equations and variables at the beginning, as in the next example. S EQ1 : {x 2*y – 1 0, -2*x 4*y^2 – 2 0}
£"2 x 4 y 2 " 2 0, x 2 y " 1 0¤ S Var1 : {x,y}
£x, y¤ S solve(EQ1, Var1)
x 2 " 5 ,y
5 2
"
1 2
, x 2 5 ,y "
5 2
"
1 2
Chapter 1 ( Introduction to MuPAD
9
We will talk about sets later at the end of this chapter. Before then, let us do a few exercises. Exercise 1.3 Declare the given equations or sets of equations and solve them with MuPAD. 1. x 2 " 49 0 2. x 2 x " 6 0 3. 20x 2 " 31x " 9 0 4. x 2 " 3x " 1 0 5. x 2 " 6x 1 0 6. x 2 7x 9 0 7. x 2 y 2 4xy " 1 0, solve in respect to the variable x, and then do the same for variable y. 8. x 3 " x 2 x 1 0, obtain the results in decimal form. Find out how to produce results in an exact form. 9. x " 2y 7 and x 2 4y 2 37 10. x y 1 and 16x 2 y 2 65 11. y " x a and 2x 2 xy y 2 8
1.4 4 Transforming mathematical expressions Transforming mathematical expressions is one of the most frequent activities starting in primary school, all the way up to advanced research. MuPAD contains a number of procedures that can help. Starting with version 3.0, we MuPAD provides powerful tools for simplifying mathematical expressions, in particular, trigonometric ones. Let us analyze a few simple examples. We declare a polynomial and see what we can do with it. S A : (x - 3)^2*(x - 1)^3*(x - 5)
x " 1 3 x " 3 2 x " 5 Next let us expand the polynomial.
10
Getting started with MuPAD
S B : expand(A)
x 6 " 14 x 5 75 x 4 " 196 x 3 263 x 2 " 174 x 45 We can get back to the beginning by factorizing the result. S factor(B)
x " 5 x " 3 2 x " 1 3 Simplification of formulas is slightly trickier. This is because the word simplify may have a different meaning for all of us and depends heavily on the given context. Let us see how MuPAD simplifies mathematical formulas. S simplify(sin(2*x)^2 cos(2*x)^2) 1 S Simplify(sin(3*x) * cos(3*x)) //Note, capital S
sin6 x 2 S simplify(exp(x)*exp(3*x)-exp(x)*exp(2*x))
e x 3 e x " 1 Technical comment Starting from version 3.0, MuPAD contains two procedures: simplify and Simplify. Their names begin with a lowercase and an uppercase “s”. The procedure simplify is sufficient for most elementary examples. The procedure Simplify is more “intelligent” and can handle more complex expressions. However, in many situations this procedure is slower. Procedures to simplify formulae may involve several parameters. For example, as in the case below, we can ask to simplify an expression with respect to a specific function. Here it is the function sqrt. S simplify(sqrt(4 2*sqrt(3)), sqrt)
3 1 MuPAD provides several procedures for manipulating polynomials. Let us define a polynomial in two variables Px, y and illustrate this point. S P : x*y a*x*y x^2*y - a*x*y^2 x a*x
x x2 y a x x y " a x y2 a x y
Chapter 1 ( Introduction to MuPAD
11
S collect(P, x) // collecting in respect to x
y x 2 a y " a y 2 a y 1 x S collect(P, y) // collecting in respect to y
"a x y 2 x a x x 2 y x a x S collect(P,[x,y]) // collecting for x and y
x 2 y " a x y 2 a 1 x y a 1 x In calculus, we often decompose rational expressions into fractions, usually called partial fractions, where the denominator contains a single irreducible polynomial of the first or second degree and the numerator is a polynomial of the degree zero or one. In MuPAD this can be done using the procedure partfrac. S w : x^2/(x^3 - 3*x 2)
x2 x "3x2 3
S partfrac(w)
5 1 4 9 x 2 9 x " 1 3 x " 1 2 Exercise 1.4
Use MuPAD to perform the required transformations.
1. Expand the expressions: a. 2x 3 2 , b. 4x 2 " 1 2 , c. x " 1 2 x " 3 4 , d. x " 2 x " 3 5 x " 4 2 , e. 1 x n , where n 2, 3, 4, 5. 2. Expand these trigonometric expressions: a. sin x cos x 3 , b.
1 sin x cos x
c. tanx 1 , d. cotx 2 1
5
,
12
Getting started with MuPAD
3. Factorize the following expressions: a. 2x 2 " 3x 3 , b. 4x 4 " 5x 2 1, c. 9x 2 21x 10, d. 6x 2 " 4x " 4x 3 x 4 1, e.
1 y1
1 2
x
1 2
1 1"y
1 2
x
1 2
4. Simplify the following expressions: a. cos x sin y cos y sin x b. 5x 10x 2 10x 3 5x 4 x 5 1 c.
1 y1
d.
1 3x 5 1 3x 3 9x
e.
1 2
x
1 2
1 1"y
1 2
x
1 2
2 " 3 , 2 3
5. Decompose the following expressions into partial fractions: a. 2 x 7 , x "x"6 2 6. b. 50x3 20x x 2x 2 x
1.5 5 Differentiation and integration Differentiation and integration are the basic operations of calculus. Of course calculus doesn’t end there. It includes a wide range of interesting topics some of which we will come to it in a chapter later on. In this chapter, we concentrate on the basics of differentiation and integration. Let us begin by defining an expression in a single variable x. S w : x^2/(x^3 - x 1)
x2 x3 " x 1 We can calculate its first derivative.
Chapter 1 ( Introduction to MuPAD
13
S diff(w,x) 2x
x 2 3x 2 "1
"
x 3 "x1
x 3 "x1
2
In the same way, we can obtain the second, third, and higher derivatives. S diff(w,x,x) 2
6x 3
"
x 3 "x1
x 3 "x1 2
2x 2 3x 2 "1 2 x 3 "x1 3
"
4x3x 2 "1 x 3 "x1 2
Here is another example, where we calculate the derivatives of a trigonometric function. S h : sin(x)/cos(x) sinx cosx
S diff(h,x,x,x) 8 sinx 2 cosx 2
6 sinx 4 cosx 4
2
In exactly the same way we can obtain the partial derivatives of an expression in two or more variables. S u : (sin(x) cos(y))*(cos(x) - sin(y))
sinx cosy cosx " siny We can produce the second partial derivative in respect to x and then y. S diff(u,x,y)
sinx siny " cosx cosy MuPAD calculates definite as well as indefinite integrals. S int(x^2 3*x 1, x) x3 3
3x 2 2
x
S int(x^2 3*x 1, x0..10) 1480 3
14
Getting started with MuPAD
Exercise 1.5 Obtain the derivaties and integrals of the given expressions. 1. y x 3 x 2 x 1 2. y sin x cos x 3. y tan x cot x 4. y e 1xx 5. y
2
1x 1xx 2
Until now, we have performed most of our operations on expressions with or without variables. However, mathematicians usually prefer to deal with functions. In the next section we will learn how to declare basic functions in MuPAD, and what the difference is between an expression in a variable and a function.
1.6 6 Declaring functions The declaration of a function in MuPAD uses a notation similar to that encountered in school mathematics. For example, f : x v 1/1 x 3 , where f is the name of the function, x is its argument, and the expression on the right side is a rule showing how to calculate values of the function f. In MuPAD, we have almost the same syntax. S f : x-1/(1 x^3)
x¯
1 1x 3
Having declared the function f, we can use it in subsequent calculations, such as S diff(f(x),x)
"
3x 2 x 3 1 2
or S int(f(x),x)
Chapter 1 ( Introduction to MuPAD
lnx1 3
"
3
ln x" 1 2 3 4 2
2 arctan
6
15 2 3 x" 1 2 3
"=
6
We can obtain the definite integral of this function on the finite interval 0 t x t 5 by executing the statement S int(f(x), x 0..5) ln6 3
"
ln21 6
= 3 18
arctan3 3 3 3
and produce the integral of f over the infinite interval x, . by executing the statement S int(f(x), x 0..infinity) 2= 3 9
Another important operation on functions is to find some of their limits. Let us check the limits of the function f above for the points x 0 and x "1. S f : x-1/(1x^3)
x¯
1 1 x3
S limit(f(x), x0) 1 S limit(f(x),x -1) undefined Although the limit of f at x "1 is undefined, we can check the one-sided limits from the left and right at this point. S limit(f(x), x -1, Left)
". S limit(f(x), x -1, Right)
. MuPAD also has tools for analyzing sequences. We treat sequences as functions with integer arguments. For example, the limit of the sequence e n 1 1/n n for n v . can be produced as follows.
16
Getting started with MuPAD
S en : n-(11/n)^n
n v 1
1 n
n
S limit(en(n), n infinity) e After having declared a function, we can use MuPAD to calculate the values of the function. Here is an example. Let f be the function used in one of our earlier examples. S f : x-1/(1x^3) 1 1x 3
To calculate the value f1. 234 , we need to execute this simple statement. S f(1.234) 0.3473330668 At this stage it is important to understand the difference between a variable, say F, declared as a formula and F declared as a function. Let us consider the example of two very similar declarations F1:x^3x^2x and F2:x-x^3x^2x. In the first case, F1 is just a label for the formula x^3x^2x. We can put it anywhere where we would put the formula x^3x^2x, for example in the statement solve(F1-10,x). The symbol F2, on the other hand, denotes a function and we should always use it with an argument, for example solve(F2(x)-10,x) or solve(F2(y)-10,y). Concluding, we cannot use F1(x) but must use F1 only, while at the same time we cannot use F2 only, we have to use it with an argument, F2(x). Exercise 1.6 Declare the following functions in MuPAD and calculate their values for x 1 and x 0. 1. fx 2. gx
1 x 1 1 2x 3x 2
3. hx x 3 2x 2 3x 4
Chapter 1 ( Introduction to MuPAD 1 1
1
4. Frx
1
5. Rtsx
x 2x 3x 4x x
1 x
17
1
1 1 1x
From time to time it happens that we must deal with functions build from pieces of two or more functions. For example, the function presented in the picture below can be treated as a function built from three pieces, with each piece determined by a different formula.
y
3
2
1
-3.0
-2.5
-2.0
-1.5
-1.0
-0.5
0.0
0.5
1.0
1.5
2.0
2.5
3.0
x
Such functions can be declared as follows: S f : x - piecewise([x-1,-x],[x1,1],[x1,x]) Declaring piecewise functions requires some thought on how to declare each piece and how the pieces connect. The order of the pieces in such declarations is crucial. We will discuss piecewise functions in detail in the chapter about calculus. MuPAD can be used to plot the graphs of declared functions. Here is an example. Let f be the function used in one of our earlier examples. S f : x-1/(1x^3)
1 1 x3 Producing the most basic plot of this function involves a simple statement.
18
Getting started with MuPAD
S plotfunc2d(f(x), x-3..2) y 2.0
1.5
1.0
0.5
-3
-2
-1
1
2
x
-0.5
-1.0
-1.5
The consideration of this example has lead us to MuPAD graphics. In the next chapter we will discuss graphics in MuPAD in detail. Here we only examine two basic examples.
1.7 7 Graphs of functions in one variable As we noticed in the previous section, obtaining the graph of a function can be quite easy and even with a simple tool like plotfunc2d we can produce sophisticated graphs. Here is another interesting example. We will produce graphs of two functions in the same coordinate system. S plotfunc2d(tan(x), cot(x), x 0..2*PI): y 4 3 2 1 0 1
2
3
-1
4
5
6
x
-2 -3 -4 tan(x) cot(x)
Exercise 1.7 Produce graphs for the given expressions or groups of expressions. 1. sin x, sin 2x, sin 3x, sin 4x 2. sin x, sin x 1, sin x 2, sin x 3
Chapter 1 ( Introduction to MuPAD
19
3. sin x, sinx 1 , sinx 2 , sinx 3 4. sin 3x cos 2x x "x 5. e e 2
1.8 8 Graphs of functions of two variables In almost the analogous way, we can produce graphs of functions in two variables. In the next example, we produce a graph of the two expressions sinx 2 y 2 and cosx 2 " y 2 . S plotfunc3d( sin(x^2 y^2), cos(x^2 - y^2), x-1.5..1.5, y-1.5..1.5 ):
Technical comment As we already know, pressing the [Enter] key inside an input region forces MuPAD to execute a statement. If for some reason we want to split our statement into two or more lines, we can create line breaks by pressing the keys [Shift] and [Enter] simultaneously. Technical comment Any two consecutive statements in the same input region must always be separated by “;" or “:" symbols.
20
Getting started with MuPAD
Exercise 1.8 Produce graphs for the given expressions or groups of expressions. 1. 1, sin x, sin 2x, sin 3x, sin 4x 2. sin xy, sin xy 1, sin xy 2, sin xy 3 3. sin xy, sinxy 1 , sinxy 2 , sinxy 3 4. xy, xy 1 , x 1 y, x 1 y 1 5. x 3 y 2 x y 6. sinx y
1.9 9 Selected mathematical structures in MuPAD In mathematics, we frequently use mathematical objects that have some internal structure, for example sequences, vectors, matrices, or sets. In order to distinguish such objects from individual numbers or symbols, we call them mathematical structures. A sequence is an ordered collection of elements. In mathematics, we use two methods to define sequences: by listing their elements or by using a formula such as a n n/n 1 . In the latter case, a sequence is treated as a function of one variable with integer or natural arguments. Here is an example of a squence A declared by listing its elements. S A : 1, -2, 3, -4, 5, -5, 6, -8, 8, -3, 4 1, -2, 3, -4, 5, -5, 6, -8, 8, -3, 4 A sequence declared this way differs significantly from a sequence declared as a function. In the first case, we deal with a collection of almost physical objects, whereas in the second case, we do not have any objects as such, but rather a recipe showing how to calculate the elements of the sequence. Sets are another type mathematical structure in MuPAD. We declare them by listing their elements and surrounding them with curly brackets. S B : {1, -2, 3, -4, 5, -5, 6, -8, 8, -3, 4}: S C : {-1, 2, 7, 4, -5, 5, 9, -8, 10, 3, -4}: Once we have declared two sets, we can perform set-theoretical
Chapter 1 ( Introduction to MuPAD
21
operations on them. S B union C {-8, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} S B intersect C {-8, -5, -4, 3, 4, 5} S B minus C {-3, -2, 1, 6, 8} Another useful structures in MuPAD are lists. Normally, lists are not considered to be mathematical structures like sequences or sets. However, lists are very useful structures for dealing with larger collections of objects. We declare them like sets by listing their elements, but we enclose them in square brackets. There are two important differences between sets and lists. In sets, the order of elements is unimportant. In lists the order of elements is important. In a set each element may occur only once. In lists we can have repeated elements. However, there is one common feature—both a set and a list can be empty. A sequence, on the other hand, cannot be empty. Here are two declarations of an empty set and an empty list. S MyEmptySet : {} S MyEmptyList : [] In order to add elements to a sequence we append them at the end, just as in the following example: S MySequence : 1,2,3,4 1, 2, 3, 4 S Sequence2 : MySequence,5,7,8 1, 2, 3, 4, 5, 7, 8 In order to add elements to a set we use union: S MySet : {a,b,c}: S MySet2 : MySet union {2,3,4,3,4} Adding elements to a list, or joining two lists, can be obtained by using the concatenation operator “.”.
22
Getting started with MuPAD
Here is an example: S List1 : [1,2,3,4] [1, 2, 3, 4] S List2 : List1.[3,4,5,6] [1, 2, 3, 4, 3, 4, 5, 6] In the following chapters, we also need to convert a list into a set or a sequence. In MuPAD there is a quick way of extracting data from a structure. Suppose, for instance, that we have the list [1,2,3] and wish to change it to the set {1,2,3} or vice versa. We can do so by using the procedure op. S A : [1,2,3]: A : op(A): A : {A}
£1, 2, 3¤ Finally let us examine the very useful operator $, which can be used to produce a sequence, set or list from a formula. In this book we will call this symbol the sequence operator. Let us consider the sequence given by the formula a n sinn =/3 . Here we show how to produce the finite sequence a n for n 2. . 10. S A : sin(n*PI/3) $ n 2..10 3 2
, 0, "
3 2
,"
3 2
, 0,
3 2
3 2
,
, 0, "
3 2
Next we convert this sequence to a list and a set. S B : [A] 3 2
, 0, "
3 2
,"
3 2
, 0,
3 2
,
3 2
, 0, "
3 2
S C : {A}
0, "
3 2
,
3 2
It is important to point out one of the most frequent errors made when using the sequence operator. We often forget to declare a proper range for the variable, as in n $ 10. In this case, MuPAD actually produces ten copies of the letter n.
Chapter 1 ( Introduction to MuPAD
23
S n $ 10 n, n, n, n, n, n, n, n, n, n We end our discussion of mathematical structures by showing how to declare matrices. There are many ways to create a matrix. Here is the simplest one. We declare a matrix as a list of three lists, with each of them having three elements. It is fairly obvious this produces a 3 3 matrix. S A : matrix([[1, 5, 5], [2, 3, 8], [2,7, 8]])
1 5 5 2 3 8 2 7 8 However, if we wish to gain more control over the creation of a matrix, we must also declare the dimensions of the matrix. Here we declare a vertical vector. S B : matrix(3, 1, [1,2,3])
1 2 3 In a similar way, we can declare a horizontal vector. S C : matrix (1, 3, [1,2,3])
1 2 3 As said before, there are many ways of creating matrices. We will discuss them in the algebra chapter. Exercise 1.9 Write the declarations of sequences, lists and sets representing: 1. all integer numbers from 5 to 25 2. all even integer numbers from 100 to 200 3. the fractions
n n1
for n 0. . 100
4. the terms of the sequence a n "1 n for n 1. . 25
24
Getting started with MuPAD
5. all numbers of the form
n , for n 10. k
1.1 10 Looking for help We tend to forget new computing terms and especially commands of a programming language. This happens also with names of procedures used in MuPAD. It is therefore worth knowing how we can quickly find out in MuPAD the proper names of procedures and how to use them in statements. Let us start with a basic help command. S info(stdlib) After executing such a statement, MuPAD displays the list of all standard procedures. In this list we can try to find a name of the procedure we are looking for, or the name of a procedure that might be useful for us in a given situation. Suppose, for example, that we are looking for a procedure to simplify an algebraic expression. In our list we find collect, combine, simplif, radsimp and a few other names worth checking. Suppose, then, that we opt for the radsimp procedure. How can we find out what this procedure can do and how to use it? Let us check out info again. S info(radsimp) radsimp – a procedure of domain type ’DOM_PROC’ This result turns out no to be helpful. But in many other situations, it actually provides useful information. Let us try something else. Let us write the name of the procedure, preceded by a question mark. S ?radsimp After executing this statement, MuPAD displays the help browser with a list of the terms containing radsimp. Once we have selected the name of our procedure, MuPAD displays detailed information about our procedure and related procedures, as well as providing examples that show how to use the procedure in a statement. Note that some words displayed in MuPAD help have a yellow background. These words are links, like links on a web page, pointing to pages with further explanations of terms or examples. In front of each example there is a
Chapter 1 ( Introduction to MuPAD
25
double arrow with a green background. By clicking it we can copy the example into our notebook. This provides us with the opportunity to carry out a number of quick experiments and to find out more about our procedures. Here is one of the examples for radsimp, copied from MuPAD help. S U : (1/2 1/4*3^(1/2))^(1/2)
3 1 2 4 S radsimp(U)
3 2 2 4 4 Now we know that radsimp can be used to simplify algebraic expressions with radicals. Another way to obtain the active vocabulary of MuPAD is the statement anames(). It prints on the screen all names that are, at the given moment, accessible in the current MuPAD notebook. This is what the output might look like: S anames() {‘*‘, ‘**‘, ‘‘, ‘-‘, ‘/‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, Ax, C_, Cat, Ci, D, Dom, E, Ei, I, Im, O, Q_, RGB, R_, Re, Si, Sum, U, Z_, ‘^‘, _if, _in, _or, abs, adt, arg, cos, cot, csc, erf, exp, fp, fun, gcd, has, id,... The list goes on and is too long for inclusion in this book. But it is worth looking at since it contains very useful information. Another problem of a MuPAD user are long or complex names of procedures. In many cases we do not remember the exact spelling of a procedure name. For example how to write sysevalassign or heaviside or assignElements. There are more words like these. In such case we can ask MuPAD to complete the name for us. In a MuPAD notebook, it is enough to type in the first two or three letters of a given name and then press [ctrl][space]. For example, let us type in the word co and then press [ctrl][space]. MuPAD will display a small window with a list of names of procedures starting with co. After selecting the right word from the list, MuPAD will complete automatically the name of the procedure.
26
Getting started with MuPAD
Fig. 1.2 Completing words in MuPAD
1.1 11 Using libraries The number of functions and procedures in MuPAD is much larger than what we can display using info(stdlib) or even anames(). As mentioned before, the command info(stdlib) displays only the standard functions and procedures. These procedures are available immediately after opening a new notebook. However, large additional collections of procedures are hidden in libraries. Each library contains procedures related to a specific branch of mathematics or to programming. For example, we have the library linalg with tools for linear algebra, the library combinat with tools for combinatorics, and the plot library containing tools for creating graphics. The statement info() displays the list of libraries available in the current version of MuPAD. This list may differ slightly from version to version. For example, in my version of MuPAD, the command info() produces the following information: S info() – Libraries: Ax, RGB, combinat, groebner, linopt,
Cat, Series, detools, import, listlib,
Dom, Type, fp, intlib, matchlib,
Graph, adt, generate, linalg, module,
Chapter 1 ( Introduction to MuPAD numeric, output, property, stdlib,
numlib, plot, solvelib, stringlib,
ode, polylib, specfunc, student,
27 orthpoly, prog, stats, transform
Examining the contents of a library is very simple. Again, the procedure info turns out to be useful. Here is what we can find out about the library student using the info procedure: S info(student) Library ’student’: the student package – Interface: student::Kn, student::equateMatrix, student::isFree, student::plotRiemann, student::plotSimpson, student::plotTrapezoid, student::riemann, student::simpson, student::trapezoid As we can see, the student library contains mostly tools for visualizing various integration methods. Another important question is how we can use the procedures provided in the libraries. Note, for example, that executing the statement simpson(sin(x),x0..PI) does not produce a meaningful result because MuPAD does not understand the statement. S simpson(sin(x),x0..PI) simpson(sin(x),x0..PI) The most natural way of using procedures from libraries is to use statements beginning with the name of the library, followed by “::”, followed by the name of the procedure, as in the next example. S student::simpson(sin(x),x0..PI) = 4
2
! i51 sin 12
S float(%)
2. 004559755
=2i5"1 4
2
28
Getting started with MuPAD
The statement written in this way forces MuPAD to open the library student and then use the simpson procedure. We call the symbol “::” the slot operator. Another way of using procedures from libraries is to export them into a notebook and then use them like any standard procedure. For example, S export(student, simpson): S simpson(x^3,x0..1) 2
! i91 i92 3
"
1 4
3
5 48
Observe that MuPAD also knows how to complete the names of libraries and procedures from libraries. Let us type stud, for example, and press [ctrl][space]. MuPAD completes the expression to student::. We then press [ctrl][space] again and select the name of the desired procedure from the given list. Exercise 1.10 1. Use MuPAD help to get information about the procedures nextprime, nthterm, partfrac, combine, taylor. Copy selected examples from the help pages to your notebook and check if you can obtain the same results.
1.1 12 Tracing basic errors It may happen that after working in a MuPAD notebook for a while, we suddenly get strange-looking results. This often leads to the suspicion that MuPAD has a bug. But before looking for errors in MuPAD, or reporting these results to SciFace as bugs, we need to learn something about the way computer algebra systems work. This will save time and avoid making unexpected mistakes. First, let us see where MuPAD keeps the data in a notebook. Every time we produce a result, MuPAD keeps it in memory, as a value assigned to a variable or as an element of a computational history. Among the variables involved are named variables, that is to say, variables declared previously.
Chapter 1 ( Introduction to MuPAD
29
For instance, we may get the following situation: S myNumber : 12 12 S nextNumber : myNumber1 13 S newNumber newNumber Both myNumber and nextNumber have been assigned a value, whereas newNumber has no value. In this case, newNumber is a free variable and every time we use it, MuPAD displays only its name. Among the errors which MuPAD users frequently make are minor spelling errors when typing the names of variables, functions or procedures. For example, it is enough to type NextNumber instead of nextNumber to produce an error. The syntax of MuPAD statements is case sensitive. Another very frequent error is to forget the colon while typing the assignment operator, typing A123 instead of A:123, for example. In this way, we may end up producing two completely different results. The expression A:123 assigns the value 123 to the variable A, while the expression A123 produces an equation that is either true or false. S is(A123) UNKNOWN Here the response can be TRUE, FALSE or UNKNOWN depending on the value of the variable A. Let us examine a typical scenario involving another type of error frequently produced by MuPAD users. Imagine that while working with MuPAD, we declared a polynomial: S p : x^2 - 3*x - 3
x2 " 3 x " 3 S p
x2 " 3 x " 3 Here p is a named variable and x is a free variable. However, suppose that in a different place in the same notebook we had assigned a value to x, for
30
Getting started with MuPAD
example x:sqrt(3). In that case, the value of p would be calculated according to the new value of x. S p
"3 3 Things may be worse: S solve(x^2 - 3*x - 3 0, x) Error: Illegal variable(s) to solve for: 3^(1/2) [solve] The situations described here are likely to occur in a notebook that contains a large number of calculations and experiments. In order to prevent such errors it is wise to free all variables used earlier before starting on a new problem or exercise. We can do so by using the delete command. S delete x Once this command has been executed, p becomes again a polynomial and solve(x^2-3*x-30,x) will again make sense. S p
x2 " 3 x " 3 Technical comment Note that we use delete without enclosing its arguments in brackets, for example delete p, q, r, s Another efficient, but slightly extreme, solution is to reset the whole notebook. S reset() Resetting the notebook removes the values of all variables and all results of calculations from the memory of the computer. Before finishing this chapter it may be helpful to say a word about histories of calculations in MuPAD. A history of calculations is a table where MuPAD keeps the results of the most recent results. Each new result is added to one end of the table and the oldest result is removed from the other end. We can access entries in the history table using the last procedure or the symbol %. Let us to illustrate how this works.
Chapter 1 ( Introduction to MuPAD
31
S A:34 34 S A:A1 35 S A^2 1225 S (A^2)^2 1500625 After these operations, the history contains the following results: 34, 35, 1225, 1500625 Now, let us execute last(1) or %1 S last(1) 1500625 Observe that this time, we added a new entry to the history 34, 35, 1225, 1500625, 1500625. Therefore, if we wish to access entry 1225, now we have to use command last(3). By default, the history of calculations contains 20 entries. Technical comment The history of calculations is a bit more complicated than described. However, due to the introductory nature of this book, we will not go into further details. Exercise 1.11 S S S S S S S S S S S S S
Consider the following MuPAD statements.
A : 1 B : 21 A : A3 B A5 u : A*3 %1 %3%2 last(2) solve(u^2 3*A 1, u) solve(x^2 3*A 1, u) delete u solve(u^2 3*A 1, u) delete A
32 S S S S
Getting started with MuPAD solve(u^2 3*A 1, u) A, B, u, x reset() A, B, u, x
1. Explain without executing these statements what the output would be in each case. 2. Create a new notebook and type each statement in a separate input region. Execute each statement and compare your answers with the output produced by MuPAD. 3. Write down all the entries of the history table for the first 10 statements.
This completes the chapter on the basic features of MuPAD. In the next chapters, we deal in depth with the use MuPAD for specific purposes, such as mathematical graphics, calculus and algebra.
Mathematical graphics with MuPAD In the previous chapter we introduced some basic MuPAD graphs. In this chapter we will explore in detail the concept of MuPAD graphics. We will learn how to create various types of graphs, how to build complex scenes with multiple graphical objects, and finally we will learn how to develop mathematical animations step by step. It is important to mention that MuPAD graphics is based on OpenGL that is a world standard for scientific graphics.
2.1 1 Secrets of the Virtual Camera One of the components of MuPAD is the Virtual Camera, VCam for short. We use this tool to display and manipulate graphics created by MuPAD. The Virtual Camera has a number of interesting features and, at the time of writing of this book, it is considered to be the most advanced tool available for working with mathematical graphics. Let us start with a graph containing some 3D surfaces. For our purposes, we will use the four functions fx, y x 2 y 2 , gx, y "x 2 y 2 , hx, y x 2 " y 2 and px, y "x 2 " y 2 . First we will declare our functions and then we will plot them in the same coordinate system. Here are declarations of our functions. f : (x,y) -
x^2 y^2:
34
Getting started with MuPAD
g : (x,y) - -x^2 y^2: h : (x,y) - x^2 - y^2: p : (x,y) - -x^2 - y^2: Now we can put them together into one statement using the plotfunc3d procedure. plotfunc3d( f(x,y), g(x,y), h(x,y), p(x,y), x-2..2, y-2..2 )
MuPAD has produced a nice picture with four intersecting surfaces. In fact, MuPAD did not do all of the work: it calculated the shapes and some of their parameters and then passed the results to the Virtual Camera. The Virtual Camera rendered the MuPAD calculations into a single graph and embedded it in our notebook. Thus, what we see on the screen is the final result of the work of two programs—MuPAD and the Virtual Camera. In the future we will see that very often the Virtual Camera can change a graph according to our needs, but in many situations we will have to ask MuPAD to recalculate the graph. More about this later. Now let us concentrate on our picture. The first and most important question is how to tell which surface represents which equation. The colors in the legend do not reflect precisely the colors of the surfaces. Let us open our graph in Virtual Camera and see what we can do. In order to
Chapter 2 ( Mathematical graphics with MuPAD
35
do this we have to right click the picture and then from a popup menu choose Graphics Object, followed by Open. We then obtain the Virtual Camera window. It may look like the one in figure 2.1. Let us take a quick look at the Virtual Camera screen elements—icons, menus and pannels—and see what we can do with them.
Fig. 2.1 The Virtual Camera window All the operations that are available through icons are also available from menus. We will therefore concentrate on icons and leave it to the reader to explore the menus. To begin with, let us observe that we can rotate our graph in any direction using the mouse pointer. We will also be able to zoom in or move it if we switch to the zoom and move modes by selecting the appropriate icon from the toolbox. The icon with the double arrow (up and down) switches to the zoom mode and the icon with four arrows switches to the move mode. We will explain all of the toolboxes a little later. Figure 2.2 displays almost all toolboxes available in Virtual Camera. There is one toolbox that
36
Getting started with MuPAD
is missing here: it is the toolbox for animation and we will see it later when we start developing animations.
Fig. 2.2 Toolboxes in Virtual Camera After a few manipulations of our graphics we are ready to examine the Virtual Camera toolboxes. In this group we have the icons for general graph manipulation. Starting from the left we have: the icon to reset the viewpoint; the icon to center the graph; two shaded icons to recalculate the graph and to stop calculations; icons to display and close panels that we see on the right side of Virtual Camera window; and finally the help icon. Icons from the second group can be used to select a graphical object, rotate it, zoom in or out, move it in any direction and read coordinates of a point on the graph. Icons in this group can be used to execute some of the graph animations that are predefined in Virtual Camera: start and stop rotating a graph left, right, down and up; zoom in or out and select the speed of animation. Now when we know the meaning of all these icons, we can move to the right side of the Virtual Camera window and explore the three panels shown here (see fig. 2.3).
Chapter 2 ( Mathematical graphics with MuPAD
37
Fig. 2.3 Panels in Virtual Camera window In the top panel, called Object Browser, we see the structure of the current graphical scene. Here we can see that the concept of MuPAD graphics is much more complicated than we could expect. Our main graphical object is Canvas; then we have another object called Scene3d, and finally inside Scene3D we have CoordinateSystem3d with four objects called Function3d. We will talk more about the structure of MuPAD graphics in the later sections of this chapter. It is worth noting that while writing the code for our graphics, we only declared the four functions. MuPAD created the remaining objects automatically for us. Moreover, we neither specified the colors of our graphs nor how they should be displayed. MuPAD therefore used some default parameters. We will see later that in many situations MuPAD uses default parameters and objects and thus allows us to simplify the required code. Let us now look on the remaining panels. The next one is the Properties panel. Here, depending on what we selected in Objects Browser, we can see the properties of a selected object. For our convenience, all the properties are grouped into a few categories and in front of the name of each group there is a small [] or [-] sign. By clicking the [] sign, we can expand the group and see all the properties included in it. For example, in figure 2.3 the first selected graphical object is Function3d and the
38
Getting started with MuPAD
selected properties group for this object is Definition. After expanding this group we obtain the panel that is shown in the middle of fig. 2.3. Here we see how the function was defined: its formula, range of variables, and many other things. Here we can also change the values of any of these parameters and obtain a graph more suited to our needs. Observe that after changing some of these properties, the Virtual Camera automatically adjusts the graph. However, in many situations we will have to ask MuPAD to recalculate the graph. Earlier I mentioned the recalculate graph icon—the one with the exclamation mark. If this icon becomes green, then this is a sign that our graph needs to be recalculated. Click the recalculate icon and wait a few seconds to get a new graph. Technical comment In the properties panel, we can change all of the properties of the graphical objects in the current scene. However, in the Virtual Camera, with some exceptions, we cannot create new objects. Therefore any object that we wish to have in our scene must be declared in MuPAD code. The only objects that can be added in the Virtual Camera are lights and user cameras. The last panel is the Current View panel. In this panel we have all the parameters of the default camera. The default camera has properties similar to a regular camera. Therefore, we can define here the location of the camera, the coordinates of the place where the camera is pointing, the angle of the lens, and a few other parameters. In the Virtual Camera, users can add their own cameras and use several different cameras in one scene. For example, one camera can show the graph from the front, another one from the top, yet another one from a very large distance using lens with a very narrow angle, and yet another one can show only some small detail. We can add a new camera from the Insert menu. The new camera captures all of the parameters from the current view. However later, we can easily adjust the individual cameras as needed. Let us return to our example. In order to familiarize ourselves with the environment of the Virtual Camera we will carry out a few small experiments. Suppose that we wish to display each surface in different color, the top one without a mesh, and the two in the middle with partial mesh only. We can also change other details, but I will leave this interesting activity to my readers.
Chapter 2 ( Mathematical graphics with MuPAD
39
Let us start by selecting in the Objects Browser the topmost Function3d. In the Properties panel we see the following groups: the definition parameters (Definition), the animation parameters (Animation), the graph annotation parameters (Annotation), parameters defining how graph was calculated (Calculation), and finally parmeters that determine how the graph is displayed (Style). Let us expand the Style group and then go to Surface. Here we change FillColorType into Monochrome and FillColor to light red 100%. Observe here that we can also make our surface partially or completely transparent by changing the opacity of the color to a value smaller than 100%. In exactly the same way, we change the colors of the remaining surfaces to Monochrome green, yellow, and blue. Now, certainly each of these surfaces will have its unique color that is shown properly in the legend at the bottom of the picture. While talking about colors, it would be convenient to describe other ways of coloring our graphs. The Flat type uses a single color for the whole surface; the Monochrome type uses also one color, but with varying color intensity, the top parts of the graph are lighter while the bottom is darker; Dichromatic uses two colors, one for the top part of the graph and another one for the bottom part, with a smooth transition between these colors; the Rainbow uses a rainbow of colors; finally, the Functional type produces a color defined by a function. I would suggest that readers experiment with different types of colors. In later examples, we will talk about functional color. I did mention already that the user can also define the opacity of the color. Opacity 100% produces an opaque graph, i.e., a graph that is not transparent, while opacity 0% produces a graph that is completely transparent. Experiments with the Virtual Camera are very useful. We can better understand how MuPAD graphs are created. I suggest to my readers to produce results that resemble the graph shown in figure 2.4. As we can easily see, inside the Virtual Camera we can adjust the view of the graph and modify the whole picture to the form we need. However, while developing multiple graphs it is sometimes convenient to include all of these features in the MuPAD code for the graph. This way we do not need to modify the graph in the Virtual Camera each time we redraw it. In
40
Getting started with MuPAD
this as well as in the next chapters we will practice declaring graphics with additional parameters.
Fig. 2.4 Final image after modifications in VCam Exercise 2.1 Write a statement to plot the graphs of y x, y x 2 , y x 3 , and y x 4 in the same coordinate system. Use the Virtual Camera to add a title and footer to this graph. Change the colors of the graphs to red, green, blue, brown. Change the width of the line to 0. 5 mm. Add different backgrounds to the canvas and to scene 2d. Examine different types of coordinate systems and grids that can be used in this example. Exercise 2.2 Write a statement to plot the graphs of the functions z x 2 y 2 , z "x 2 " y 2 and z x 3 y 3 in the same coordinate system. Use the Virtual Camera to change the color of the first surface to monochrome red, the color of the second surface to monochrome blue, and make the third surface 50% transparent. Choose a coordinate system and grids that enhance the readability of the graph. Add an appropriate header and footer.
Chapter 2 ( Mathematical graphics with MuPAD
41
2.2 2 The structure of MuPAD graphs We have already noticed that graphs obtained in MuPAD may have a quite complex structure. In this section we will investigate the structure of MuPAD graphs. Each graph obtained in MuPAD is like a collection of boxes that contain other boxes, and so on. The largest container is the Canvas. It contains all the other graphical objects. We can treat the canvas like a whiteboard or a sheet of paper on which we stick graphs and titles. We can paint it or add a frame to it. The canvas may contain one or more independent scenes. Scenes can be placed on the canvas in a regular grid with rows and columns. If we do not declare the number of rows and columns, MuPAD will use its default parameters. In one of the later examples we will show how to place multiple scenes on one canvas. Scenes should have an assigned type, Scene2d or Scene3d. Each scene contains one coordinate system. However, we may not wish to show the coordinate axes on the picture. Consequently, scenes 3D must have a 3D coordinate system and scenes 2D must have 2D coordinate system. We cannot mix 2D objects with 3D objects in one scene. In a given coordinate system we may also have several graphs. These can be graphs of functions, parametric functions, implicit equations, geometric objects and many others. In 3D scenes, we may use several cameras, as well as several types of lights. Both lights and cameras are declared inside the scene coordinate system. As we mentioned before, all graphical objects, excluding lights and cameras, must be declared in MuPAD code. We do not need to declare canvas, scenes, and coordinate systems. MuPAD creates them automatically for us. Lights and cameras can be added while modifying graphics in the Virtual Camera.
2.3 3 The gallery of mathematical plots The two procedures plotfunc2d and plotfunc3d are the only elements of MuPAD graphics that we have used so far. It is important to mention that most graphical objects in MuPAD are declared in the plot library. Occasionally, we can find something that can be plotted in other
42
Getting started with MuPAD
libraries, but the plot library is the place where we should look for graphics. I have been using the term graphical object from the beginning of this book. In fact, MuPAD graphics is object-oriented in exactly the same sense as all modern programming languages are. So, while creating graphics, our major goal is to create a graphical object, or a collection of graphical objects, put them on the stage and finally plot them. Creating graphical objects is our primary goal. Plotting them is secondary. In order to better understand the concept of MuPAD graphics, let us examine a bicycle, an object from real life. Given a bicycle, we can put it anywhere, make a copy, change its wheels, paint its handlebar, and perform a number of other tasks. We can then put a collection of bicycles together, let us call it a scene, add a few lights and perhaps a few cameras, and finally take a photograph of them. Each graphical object in MuPAD is like this bicycle. We can perform almost the same operations on graphical objects as we did with the bicycles. The resulting picture is like the photograph of our collection of bicycles—it shows our graphical objects in a given environment. MuPAD applies the object-oriented concept consistently to all things created with it. However, graphics is the place where we can easily notice it and appreciate it most. Graphical objects in MuPAD may contain other objects and have specific properties. For instance, a surface in 3D contains a mesh and the patches filling it out. The mesh lines may have specific thickness, color and transparency. We can access each of these elements through the slot operator “::”. Suppose that we wish to change the color of the mesh in the surfaces representing the functions of two variables. In that case, we use a syntax similar to the one below. Here the plot library is treated as a large object containing all the other graphical objects. plot::Function3d::LineColorRGB::Blue The above statement is just an example. While declaring a graphical object, we place such declarations inside the object declaration. That way we can simplify the above code to LineColorRGB::Blue. Technical comment In this book we use two terms: a class of graphical objects, also simply called a class, and a graphical object.
Chapter 2 ( Mathematical graphics with MuPAD
43
For example, the expression ‘class Function3d’ will mean a class of all the graphical objects declared using the word Function3d and an appropriate syntax. The word Function3d will be used as a name for this class. At the same time, the term ‘graphical object’ will mean any object that was declared using the names of classes from the plot library and an appropriate syntax. We can learn about the contents of the plot library by executing the statement info(plot). Here is a small portion of the output. S info(plot) Library ’plot’: graphical primitives and functions for two- and three-dimensional plots – Interface: plot::Bars2d, plot::Bars3d, plot::Box, plot::Boxplot, plot::Circle2d, plot::Circle3d, plot::Cone, plot::Curve2d, plot::Curve3d, plot::Cylinder, plot::Cylindrical, plot::Density, plot::Dodecahedron, plot::Ellipse2d, plot::Ellipsoid, plot::Function2d, plot::Function3d, plot::Group2d, plot::Group3d, plot::Hatch, plot::Hexahedron, plot::Histogram2d, plot::Icosahedron, plot::Implicit2d, plot::Implicit3d, plot::Inequality, plot::Line2d, plot::Line3d, plot::Listplot, plot::Lsys, plot::Matrixplot, plot::Octahedron, plot::Parallelogram2d, plot::Parallelogram3d, plot::Piechart2d, plot::Piechart3d, plot::Plane, plot::Point2d, plot::Point3d, plot::PointList2d, plot::PointList3d, plot::Polar, plot::Polygon2d, plot::Polygon3d, plot::Rectangle, plot::Rotate2d, plot::Rotate3d, plot::Scale2d, plot::Scale3d, plot::Scene2d, plot::Scene3d, plot::Sphere, plot::Spherical, plot::SpotLight, plot::Sum, plot::Surface, plot::SurfaceSet, plot::Tetrahedron,
44
Getting started with MuPAD plot::Text2d, plot::Transform2d, plot::Translate2d, plot::Tube, ...
plot::Text3d, plot::Transform3d, plot::Translate3d, plot::Turtle,
The plot library is the most rapidly developing part of MuPAD. Each new version of the program contains a number of additions. Therefore, I suggest to the readers to execute the statement info(plot) and check the contents of the plot library in their version of MuPAD. In the remaining part of this chapter, I will explore graphical classes in MuPAD. However, due to limited space and the introductory nature of this book, I will use only selected classes and I will limit our investigations to very simple examples. A number of more complex examples can be found in my book MuPAD Pro Computing Essentials published by Springer Verlag or on the web pages for my books, in the examples section, at http://majewski.mupad.com
2.3.1 Function2d The class Function2d represents all the graphical objects that are graphs of functions of one variable. The procedure plotfunc2d, used earlier, provides a shortcut to Function2d. Here is an example of a declaration using the Function2d class. G1 : plot::Function2d(sin(x), x-5..5) Here we access the class Function2d with the slot operator from the plot library, then we specify the formula of the function and finally the range for the variable x. This way, we can declare a number of graphical objects and plot them in the same coordinate system. Here is an example. G1 : plot::Function2d(sin(x), x-5..5, LineColorRGB::Blue, LineWidth0.3*unit::mm ): G2 : plot::Function2d(sin(2*x), x-5..5, LineColorRGB::Red, LineWidth0.6*unit::mm ): G3 : plot::Function2d(sin(3*x), x-5..5,
Chapter 2 ( Mathematical graphics with MuPAD
45
LineColorRGB::Brown, LineWidth0.8*unit::mm ): G4 : plot::Function2d(sin(4*x), x-5..5, LineColor[0.5, 0.5, 0.5], LineWidth1*unit::mm ): plot(G1,G2,G3,G4) // here we plot objects G1,..,G4 y
1 0.8 0.6 0.4 0.2
-5
-4
-3
-2
-1
1 -0.2
2
3
4
5
x
-0.4 -0.6 -0.8 -1
Notice how we declared the color of the line and its thickness. We declare a single color by giving a list of three or four numbers from the interval ¡0, 1¢. For example, let us declare the following color: [0.54,0.67,0.99,0.67]. In this case, we have declared the three major components of our color—the amount of red, green and blue. By declaring color [0,0,0] we produce a completely black color as no color paints were used. On the other hand, by using the full amount of each component [1,1,1], we produce white. The fourth parameter in the list determines the opacity of the color. Here 1 means a completely opaque color, whereas 0 means complete transparency. The numbers between 0 and 1 produce various degrees of transparency. At the moment, colors for 2D objects cannot be transparent. However, using the four-element color declaration for them causes no harm. We can also use a color that
46
Getting started with MuPAD
was predefined in the RGB library, for example by declaring it as RGB::Red. Note the syntax used here—RGB::Red with the slot operator. While exploring the Virtual Camera we learned that we can color our surfaces in many ways, using more than a single color. The most interesting is the functional color. We will investigate it later when we have a better opportunity for using it. In MuPAD, all units are defined in the unit library. In our example, the declaration LineWidth0.3*unit::mm means exactly 0. 3mm. Other units that might be useful for our example could be unit::point or unit::cm. The default unit for the thickness of lines is mm. Exercises 2.3 1. Use the class Function2d to produce a graph of the equation y 2x " 12 . 2. Produce a graph of the function y sin = x for x "1. . 1. Find out in Virtual Camera how could you make this graph more accurate near x 0? Hint: check XMesh in Calculation. 3. Produce the graphs of the given functions using Function2d class. Each function should be plotted in a separate picture. a. y 1 cos26x 1x b. y sin 3x cos 5x c. y sin x2 1"x 2 d. y 1 2x " x sin x 1
2.3.2 Curve2d In MuPAD, we can plot curves that are defined using parametric equations. For this purpose, we use the class Curve2d. Below, I show how to declare a graphical object representing a curve defined by the parametric equations x 2 sin 3t, y 4 cos 5t. Observe that the parametric equations we place in a square bracket, thus forming a list with two components.
Chapter 2 ( Mathematical graphics with MuPAD
47
C1 : plot::Curve2d( [2*sin(3*t), 4*cos(5*t)], t0..2*PI ): plot(C1) y
4 3 2 1
-2
-1.5
-1
-0.5
0.5
1
1.5
2
x
-1 -2 -3 -4
Exercise 2.4 1. The parametric equations x cos at and y sin bt, where a and b are constants, describe a family of curves known as Lissajou curves. Obtain the graphs of a few Lissajou curves. Find a few values of a and b that produce the most interesting graphs. 2 2. A curve has the parametric equations x 1 " t 2 and y 2t 2 , 1t 1t where ". t .. Plot a graph of this curve using Curve2d class and t-5..5.
3. Obtain a graph of the cycloid x at " sin t , y a1 " cos t , where 0 t 4=.
2.3.3 Polar coordinates Mathematicians very often plot curves in polar coordinates. In such cases, usually the curve is given by the equation r f) , where ) is the angle between the x-axis of the coordinate system and the vector r connecting a point of the curve to the center of the coordinate system. The variable ) may take values from ". to .. The number r is the length of the vector r
48
Getting started with MuPAD
and it may take positive or negative values. Here I show a few examples of curves plotted in polar coordinates. We use default colors as well as default units. P1 : plot::Polar([1, alpha], alpha0..2*PI, LineWidth0.3 ): P2 : plot::Polar( [sin(2*alpha), alpha], alpha0..2*PI, LineWidth0.5 ): P3 : plot::Polar([exp(-1/u),u], u0.1..4*PI, LineWidth1 ): plot(P1, P2, P3, ScalingConstrained) y
1 0.8 0.6 0.4 0.2
-1
-0.8 -0.6 -0.4 -0.2 -0.2
0.2
0.4
0.6
0.8
1
x
-0.4 -0.6 -0.8 -1
Exercise 2.5 1. Plot the equations r 2 sin 2 and r 2 cos 2 for 0 t 2 t 2= in the same polar coordinate system. In the final plot statement use ScalingConstrained in order to get proper proportions of the graph. 2. Let us consider a family of curves in the polar coordinate system r sin n2, where n 3. . 10 and 0 t 2 t 2=. Graphs of these curves
Chapter 2 ( Mathematical graphics with MuPAD
49
are known as n-petalled roses. Plot all of them in the same coordinate system using the Polar class. 3. The equation r A B cos n2 C D sin p2 , where n, p, A, B, C and D are integer numbers, presents a family of curves. Plot the graphs of several curves from this family.
2.3.4 Implicit2d Another very important type of plots are plots of curves defined by implicit equations. Plotting graphs of implicit equations is one of the most difficult tasks. Algorithms for creating such graphs are very complex and obtaining graphs usually takes more time than producing other graphical objects. In many situations we have to use the Mesh parameter to improve the graph accuracy, e.g. Mesh[100,100]. Here is an example illustrating the use of the Implicit2d class. I1 : plot::Implicit2d(x^2y^21, x-2..2, y-2..2, LineColorRGB::Red ): I2 : plot::Implicit2d(x^2-y^21, x-2..2,y-2..2, LineColorRGB::Blue, LineWidth0.5 ): I3 : plot::Implicit2d(x^4y^41, x-1..1, y-1..1, LineColorRGB::Green, LineWidth0.7 ): I4 : plot::Implicit2d(-x^2y^21, x-2..2,y-2..2, LineColorRGB::Brown, LineWidth0.9 ): plot(I1, I2, I3, I4, ScalingConstrained)
50
Getting started with MuPAD y
2
1
-2
-1
1
2
x
-1
-2
Exercise 2.6 Use the Implicit2d class to plot graphs of the curves given by the following implicit equations. 1. x cos x y cos y 0 2. x sin x y cos y 0 3. x cos x y sin y 0 4. x cos y y cos x 0 5. x cos y y sin x 0
2.3.5 Function3d We will start with 3D graphs from the most popular 3D class, which is Function3d. With Function3d we produce exactly the same object that we produced while using the procedure plotfunc3d. However, this time we obtain a graphical object that can be used in complex scenes together with other types of graphical objects. We already know a lot about objects representing surfaces obtained from functions of two variables. Therefore we will now concentrate on something else. We will use this opportunity to learn how to use colors defined by a function. From our earlier observations it is easy to conclude that any function that defines the colors of a curve or a surface should produce three- or four-element lists with numbers from the interval ¡0, 1¢. The first three elements of this list should define the amount of red, green and blue
Chapter 2 ( Mathematical graphics with MuPAD
51
colors. The fourth element, if it exists, will describe the opacity of the given colors. Therefore, it may happen that different colors of the graphical object may have different opacity. Now let us think about the arguments of the color function. Suppose that we are going to use it to color a 3D surface. In such a case, we would have different colors for each point of the space or for each point of the surface. Let us remind ourselves that when using Function3d, each point of the surface has coordinates x, y, z . Therefore, the points of the space and the points on the surface involve the same type of coordinates. However, the situation may change for other graphical objects, e.g., for parametric surfaces. Let us define a function with three arguments x, y, z that produces color values. An example of such a function is the function Kx, y, z defined as follows K : (x,y,z)-[abs(sin(x)),abs(sin(y)),abs(sin(z))]: Such a function produces a 3D color space and our graph will be embedded in this space, as in a bucket of poorly mixed paint. Each value of this function is a triple of numbers from the interval ¡0, 1¢. Let us enter some simple declarations and see what the final result will look like. In our example, the final graph was rotated in the Virtual Camera to show better colors defined by the color function K. K : (x,y,z)-[abs(sin(x)), abs(sin(y)), abs(sin(z))]: F1 : plot::Function3d( 1.7*x*exp(-1/2*(x^2y^2)), x-4..4, y-4..4, FillColorFunctionK ): F2 : plot::Function3d(-1, x-4..4, y-4..4): plot(F1, F2)
52
Getting started with MuPAD
While considering the colors defined by a function it is useful to see, at the same time, how transparency affects the graph. Let us generate the same graph again, but this time let us add the fourth color value for opacity. For this purpose, we will use abs(sin(z)). Therefore the opacity will depend on the height of the points on the graph. The points where sinz takes values 1 or "1 will be completely opaque, the points where sinz takes value 0 will be completely transparent, and the points in between will be partially transparent. K : (x,y,z)- [abs(sin(x)),abs(sin(y)),abs(sin(z)),abs(sin(z))]: F1 : plot::Function3d( 1.7*x*exp(-1/2*(x^2y^2)), x-4..4, y-4..4, XMesh50, YMesh50, FillColorFunctionK ): F2 : plot::Function3d(-1, x-4..4, y-4..4): plot(F1, F2)
Chapter 2 ( Mathematical graphics with MuPAD
53
Technical comment MuPAD uses OpenGL technology to render graphs in 3D. This technology has some limitations. One of them is the absence of the concept of transparency. Therefore, in the Virtual Camera, transparency is simulated through another OpenGL feature. As a result we have a side effect shown on the last graph. Once applied, transparency will make the whole surface transparent even for those points where the last coordinate of color is equal to 1. This can clearly be seen in the picture below. The paraboloid was defined so that the top part of the surface is completely transparent (the last coordinate of the color is equal 0) and the bottom part is completely opaque (the last coordinate of the color is equal to 1).
54
Getting started with MuPAD
Exercise 2.7 functions.
Use the class Function3d to obtain graphs of the given
1. fx, y sin x cos y 2. fx, y sinx 3 " y 3 3. fx, y cos 7y 2 sin 3x 2 4. fx, y
xyx 2 " y 2 x2 y2
5. z 4 " x 2 " y 2 6. z x 2 y 2 " 3x 4y 2 7. z 2x 2 10x 3y 3 " 6y 2 1 1 8. z 1 cos x sin y 9. z x 2 " y 2 e "x
2 "y 2
2.3.6 Surfaces As we have noticed already, many interesting mathematical objects that can be defined using parametric equations. This also applies to surfaces in 3D. In order to declare a surface using parametric equations, we need three functions and each of them should be a function of two parameters: x xu, v , y yu, v and z zu, v . In this case, we can declare a color function that depends exclusively on the parameters u and v. Below we show an example of a parametric surface with a color function that uses only surface parameters. To declare a parametric plot of a surface in 3D we use the Surface class. Cl : (u,v)-[u-trunc(u), v-trunc(v), 0]: S1 : plot::Surface( [sin(u)*sin(v), sin(u)*cos(v), cos(u)*sin(v)], u0..PI, v0..PI, FillColorFunctionCl ): plot(S1)
Chapter 2 ( Mathematical graphics with MuPAD
55
Exercise 2.8 Use the Surface class to obtain graphs of the following parametric equations. 1. x, y, z u sin u cos v, u cos u cos v, "u sin v , where u 0. . 2= and v 0. . =. 2. x, y, z sin u, sin v, sinu 2 2v 2 , for u "3. . 3, and v "3. . . 3. 3 3 3. x, y, z u " u uv 2 , v " v vu 2 , u 2 " v 2 , where u "2. . 2 and 3 3 v "2. . 2.
4. x, y, z 2 sin u sin 2v, 2 sin 2u cos 2 v, 2 cos 2u cos 2 v , where u "=/2. . =/2 and v "=/2. . =/2. 5. x, y, z u cos v, u sin v, cosuv , where 0 t u t 2= and 0 t v t 2=. 6. x, y, z cos u sin v, t sin u sin v, cos v logtan
v 2
0. 2u , where
u 0. . 4= and v 0. 001. . 2.
2.3.7 Implicit3d We already know implicit plots in 2D. In almost exactly the same way, we can produce graphs of implicit equations in 3D. For this purpose, we need an implicit equation with three variables. Graphs of such equations are
56
Getting started with MuPAD
surfaces in 3D. For example, the well-known implicit equation x 2 y 2 z 2 1 defines a sphere with the center 0, 0, 0 and radius 1. In order to produce a plot of an implicit equation with three variables we use the Implicit3d class. Below we show an example of a Steiner surface, also known as a Roman surface. In our example, we use a simplified implicit equation y 2 z 2 z 2 x 2 x 2 y 2 2xyz 0. Obtaining its graph takes a lot of time. This is because the algorithm that produces graphs of implicit equations is quite complex. The mesh on the surface reflects the complexity of the calculations. Steiner : plot::Implicit3d( y^2*z^2 z^2*x^2 x^2*y^2 2*x*y*z 0, x-1..1, y-1..1, z-1..1, MeshVisibleTRUE, XMesh25, YMesh25, ZMesh25 ): plot(Steiner, AxesNone, ScalingConstrained)
Another disadvantage of implicit plots is their inaccuracy. For example, the above graph shows some unexpected holes and ragged surfaces. This should not happen with the Steiner surface. Therefore, we should avoid using implicit plots as much as possible, replacing them with parametric plots or plots in the spherical coordinate system. In our case, we can
Chapter 2 ( Mathematical graphics with MuPAD
57
easily transform the implicit equation of a Steiner surface to the parametric form x sin 2u cos v 2 y sin u sin 2v z cos u sin 2v For such an equation, we obtain a nice and smooth surface. The plotting time is also shorter than that for implicit plots. Therefore, we can afford to use a color function and a very dense mesh. Cl : (u,v,x,y,z)-[abs(x),abs(y),abs(z)]: SteinerParam:plot::Surface( [sin(2*u)*(cos(v))^2, sin(u)*sin(2*v), cos(u)*sin(2*v)], u-PI/2..PI/2, v-PI/2..PI/2, FillColorFunctionCl, ScalingConstrained, UMesh50, VMesh50 ): plot(SteinerParam, AxesNone)
58
Getting started with MuPAD
2.3.8 Spherical coordinates Plots in spherical or cylindrical coordinate systems provide another way for producing graphs of surfaces that may not have a functional representation in Cartesian coordinates. Graphs in spherical coordinates are especially intriguing. In practice, a plot in spherical coordinates means wrapping a graph of a function of two variables around the center of the coordinate system. Such graphs are usually very accurate and even very simple equations may produce interesting shapes. Here is a very simple example. The equation z xy plotted as a Function3d does not produce anything interesting. However, the same equation r uv, in spherical coordinates, produces a very interesting surface resembling a snail shell. Here is our equation plotted in spherical coordinates, with yet another color function. The color function does not have a mathematical value. However, it can be interesting from an artistic point of view. In this example, we display the Cartesian coordinate system with the axes passing through the point 0, 0, 0 , AxesOrigin. This helps us to locate the surface in space. p : x - abs(5*x - trunc(5*x)): Cl : (u,v,x,y,z)-[p(x*y),p(y*z),p(z*x)]: Shell : plot::Spherical( [u*v,u,v],u0..2*PI,v0..PI, FillColorFunctionCl ): plot( Shell, AxesOrigin, AxesLineWidth0.7, AxesTipsTRUE )
Chapter 2 ( Mathematical graphics with MuPAD
59
For readers who do not have much experience with spherical coordinates it would be interesting to investigate the role of both parameters in forming the shape of the surface. We can achieve this by changing the range for each of the parameters. For example, by using u0..PI/4, u0..PI, u0..3*PI/2 and u0..2*PI, we can find out how the shape of the surface changes, depending on the parameter u. Here we show a few pictures of our surface for different ranges of u. Each of these graphs was rotated in the Virtual Camera is such a way that we look at the surface from the positive end of the z-axis. I would suggest that readers try producing similar graphs by also varying the range of the parameter v.
60
Getting started with MuPAD
Exercise 2.8 Use the Spherical class to obtain graphs of the following functions in spherical coordinates. 1. r 1. 2 I sin A2, where A 1, 2, 3, . . . 7, I "1. . 2=, and 2 0. . =. 2. r I sin 22, where I 0. . = and 2 0. . 2=. 3. r o cos 2 2I sin 2 22 , where I 0. . 2= and 2 0. . = 4. r 1. 3 I tan 2, where I "1. . 5= and 2 " =4 . .
= 4
5. r 1. 2 I sin 2 2 , where I "1. . 2=, and 2 0. . = 6. r 1. 2 I sin 2 3 , where I "1. . 2=, and 2 0. . =
2.3.9 Cylindrical coordinates Most mathematics textbooks contain little information about cylindrical coordinates. We can find some basic definition of the cylindrical coordinate system, sometimes one or two examples and that is all. I would suggest to MuPAD users to spend more time plotting graphs of functions in cylindrical coordinates and explore the shapes we can produce. Meanwhile, let us update our knowledge of cylindrical coordinates. Cylindrical coordinates are a simple combination of polar coordinates for the xy-plane and Cartesian coordinates for the z-axis. Each point P has three coordinates r, theta, z , where r and theta are polar coordinates of the projection of the point P on the xy-plane and z is the coordinate of the point P on the z-axis. Therefore, a typical equation of a function in spherical coordinates may have the form r rtheta, z , where r, theta and z are as described above.
Chapter 2 ( Mathematical graphics with MuPAD
61
Suppose that we have a surface with the equation r 1, with theta ¡0, 2=¢ and z ¡0, 1¢. We can easily discover that we are dealing here with a vertical cylinder of radius of 1 and a height equal to 1. A simple calculation allows us to check that this cylinder can also be described with the implicit equation x 2 y 2 1, which is much more difficult to plot. Therefore, plots in cylindrical coordinates may be useful in many situations where the surface equation was given by an implicit formula. Plots in cylindrical coordinates are interesting in their own right. Here is a very simple equation r 3 sin2z 2 cos32 , where 2, z ¡0, =¢. We will plot it using the Cylindrical class. Cl2 : (t,z)-[abs(1-z/PI),abs(1-t/PI),abs(t/PI)]: Cy1 : plot::Cylindrical( [3*sin(2*z)2*cos(3*t), t, z], t0..PI, z0..PI, ScalingUnconstrained, FillColorFunctionCl2 ): plot(Cy1)
In MuPAD, plots in polar, spherical or cylindrical coordinate systems have a very interesting property that is not known to a wider audience.
62
Getting started with MuPAD
We can suppose that our variables are functions of some other parameters. This way, we will get parametric plots in polar, spherical or cylindrical coordinates. I am sure that this is a completely new world for many readers of this book. Therefore, let us produce an example of a parametric plot in cylindrical coordinates. Plots in polar or spherical coordinates can be declared in similar way. The example enclosed below demonstrates in spherical coordinates the plot of a surface given by the parametric equations r tv, theta sin t, z sin v. In the resulting graph, the axes of the coordinate system were removed in the Virtual Camera. Cl2: (u,z) - [abs(1-z/PI) ,abs(1-u/PI),abs(u/PI)]: Hat : plot::Cylindrical( [t*v, sin(t), sin(v)], t-2*PI..2*PI, v0..2*PI, ScalingUnconstrained, FillColorFunctionCl2, UMesh50, VMesh50 ): plot(Hat)
Chapter 2 ( Mathematical graphics with MuPAD Exercise 2.9
63
Plot the following equations in cylindrical coordinates.
1. r 1 with theta 0. . 2= and z "1. . 1 2. r z with theta 0. . 2= and z "1. . 1 3. r zu with theta 0. . 2= and z "1. . 1 4. r zu/10 with theta 0. . 4= and z "1. . 1 5. z r 2 with theta 0. . 2= and r 0. . 3 6. z sin 3r with theta 0. . 2= and r "3. . 3
2.3.10 Curve3d and Tube We know quite a lot about curves in a plane. However, our knowledge about curves in 3D is very limited. The reason is that drawing graphs of 3D curves on paper is difficult. In MuPAD, with the Virtual Camera we can obtain such graphs easily, use different means to emphasize different parts of a curve, and manipulate and even animate them. Curves in the Virtual Camera can even have variable thickness and this makes them still more interesting. In MuPAD we have two plot classes to develop graphs of curves in 3D. These are Curve3d and Tube. We can easily guess that Curve3d is just for plotting a curve in 3D. The class Tube allow us to develop graphs of curved cylinders with our curve as the core of a cylinder with a given radius. While plotting a tube, we can actually declare its radius as a function. Let us start with the equations of a curve in 3D: x r sin at cos bt, y r sin at sin bt, z r cos at. Here we show how to set up a graph of this curve, with the parameters a, b and r declared at the beginning of our code. Every time we change the values of these three parameters, we get a different curve. a b r x y z
: : : : : :
7: 3.5: 5: t - r*sin(a*t)*cos(b*t): t - r*sin(a*t)*sin(b*t): t - r*cos(a*t):
64
Getting started with MuPAD
C3D : plot::Curve3d([x(t),y(t),z(t)], t0..2*PI/b, LineWidth0.8, LineColorTypeDichromatic ): plot(C3D)
I suggest to the readers to explore this graph for different values of parameters a and b. In some cases, it may be necessary to adjust the value of the UMesh parameter. For instance, for large values of a or b we may sometimes need to use UMesh1000. Otherwise our graph will end up being built in segments. Let us produce our curve again, but this time as a tube with a radius equal to 0. 2. a b r x y z
: : : : : :
7: 3.5: 5: t - r*sin(a*t)*cos(b*t): t - r*sin(a*t)*sin(b*t): t - r*cos(a*t):
T3D : plot::Tube([x(t),y(t),z(t)], 0.2, t0..2*PI/b): plot(T3D, ScalingUnconstrained)
Chapter 2 ( Mathematical graphics with MuPAD
65
Now we can easily see the shape of the curve and analyze the role of the parameter t. We then replace the radius of the tube, here 0. 2, by a function of the parameter t. In doing so, we produced a tube with variable radius. The final picture was adjusted in the Virtual Camera. We changed the coordinate system, and the picture was rotated about the z-axis. a : 7: b : 3.5: r : 5: x : t - r*sin(a*t)*cos(b*t): y : t - r*sin(a*t)*sin(b*t): z : t - r*cos(a*t): T3D : plot::Tube( [x(t),y(t),z(t)], sin(t*b)/2, t0..2*PI/b ): plot(T3D, ScalingUnconstrained)
66
Getting started with MuPAD
Exercise 2.10 1. Use the Curve3D class to plot the following equations in 3D a. x, y, z 3 sin t, t, 3 cos t , where t "3=. . 4= b. x, y, z 4 cos t, 4 sin t, sin t cos t , where t 0. . 2= c. x, y, z
2 cos
3 2
t cos t, 2 cos
3 2
t sin t, sin
3 2
t , where
t 0. . 2= d. x, y, z t, sin 5t, cos 5t , where t 0. . 2= e. x, y, z sin t, cos t, cos 8t , where t 0. . 2= 2. Use the Tube class to plot the equations from the previous exercise. Choose your own radii for the tubes.
2.4 Plotting geometry models Until now, we have been exploring mathematical plot objects that can be declared using various types of formulas. However, in mathematics, particularly in geometry, we often deal with objects that are constructed from points, segments and polygons. In MuPAD we can also create such objects. However, it is sometimes tedious to declare all the components for a complex model, for example for a solid with 20 vertices and many polygons. Later, we will learn the basics of programming and invent
Chapter 2 ( Mathematical graphics with MuPAD
67
another way of building complex geometry objects. Meanwhile, let us learn the basic elements that we might need in the future. As we know, geometers have for centuries been using points, lines and planes to create amazing geometry worlds. Therefore, it is important to learn how we can use points, lines and planes. Let us start with points and lines in 2D.
2.4.1 Points, lines and polygons In MuPAD, we can create points and segments as well as objects related to them. In the plot library, there are four classes that might be very useful in geometric constructions. These are Point2d—the class used to create points on the plane, Line2d—the class used to create line segments in 2D, PointList2d—the class used to create lists of points on the plane and finally a class to create a polygon in 2D using point coordinates—Polygon2d. In more complex constructions, where we frequently have to use groups of elements, the Group2d class can be a valuable tool. In MuPAD, in order to declare a 2D point we use the syntax plot::Point2d([x,y]), where x, y are the coordinates of a point. Note that in MuPAD, and in computer graphics in general, a point means a lot more than a point in geometry. Here a point may have additional specific properties such as color and size. In a very similar way, we declare lines, or rather line segments, as plot::Line2d([x1,y1],[x2,y2]), providing the coordinates of the two endpoints. We can group the existing plot objects P1,P2,P3,..,Pn into one object by using the plot::Group2d(P1,P2,P3,..,Pn) statement. Let us develop a simple example using points, segments and groups. In our example, we start with the declarations for the coordinates of three points. Later we add, step by step, points, lines joining these points, another group of points, etc. Here is the result of our work. I suggest to the readers to analyze, line by line, the enclosed code and try to understand the meaning of each declaration.
68
Getting started with MuPAD
// point coordinates x1 : -1: x2 : 1: x3 : 0: y1 : -1: y2 : -1: y3 : 1: // declarations of 2D points point1 : plot::Point2d([x1,y1]): point2 : plot::Point2d([x2,y2]): point3 : plot::Point2d([x3,y3]): points : plot::Group2d( point1, point2, point3, PointColor[0,0.5,1], PointSize 3*unit::mm ): // sides of the triangle side1 : plot::Line2d([x1,y1],[x2,y2]): side2 : plot::Line2d([x2,y2],[x3,y3]): side3 : plot::Line2d([x3,y3],[x1,y1]): sides : plot::Group2d( side1, side2, side3, LineWidth1 ): // midpoints of sides midpoint1 : plot::Point2d([(x1x2)/2,(y1y2)/2]): midpoint2 : plot::Point2d([(x2x3)/2,(y2y3)/2]): midpoint3 : plot::Point2d([(x1x3)/2,(y1y3)/2]): midpoints : plot::Group2d( midpoint1, midpoint2, midpoint3, PointColor[1,0.5,0], PointSize 3*unit::mm ): // medians median1 : plot::Line2d([x1,y1],[(x2x3)/2,(y2y3)/2]): median2 : plot::Line2d([x2,y2],[(x1x3)/2,(y1y3)/2]): median3 : plot::Line2d([x3,y3],[(x1x2)/2,(y1y2)/2]): medians : plot::Group2d( median1, median2, median3, LineColor[0.8,0,0], LineWidth0.5 ):
Chapter 2 ( Mathematical graphics with MuPAD
69
plot(sides, medians, midpoints,points, ScalingConstrained, AxesNone )
Our construction required a bit of work. However, we could skip the declarations of colors, line widths, etc. We could add these later in the Virtual Camera. Now, let us look at points and lines in 3D. The principles are exactly the same. The statements for declaring points and segments are almost the same, except that, where it makes sense, we have to change 2d into 3d. In our next example we will use also polygons in 3D. Technical comment As we have already mentioned, MuPAD graphics is based on OpenGL. Therefore most of OpenGL limitations have some impact on our constructions. One of them is that in 3D we cannot use filled polygons with more than three vertices. Therefore, in most of 3D constructions any filled flat polygon with more than three vertices should be developed as a collection of filled triangles. Let us try to construct a simple triangular prism using points, lines and polygons in 3D. We will deliberately leave our construction unfinished, giving the readers an opportunity to complete the work. Here is our example.
70 // x1 y1 zd
Getting started with MuPAD point coordinates : -1: x2 : 1: x3 : 0: : -1: y2 : -1: y3 : 1: : -1: zg : 1:
// bases declaration top : plot::Polygon3d( [[x1,y1,zg], [x2,y2,zg],[x3,y3,zg]], ClosedTRUE, FilledTRUE ): bottom : plot::Polygon3d( [[x1,y1,zd], [x2,y2,zd],[x3,y3,zd]], ClosedTRUE, FilledTRUE ): // one side declaration tr1 : plot::Polygon3d( [[x1,y1,zd], [x2,y2,zd],[x2,y2,zg]], ClosedTRUE, FilledTRUE, LinesVisibleFALSE ): tr2 : plot::Polygon3d( [[x1,y1,zg], [x2,y2,zg],[x1,y1,zd]], ClosedTRUE, FilledTRUE, LinesVisibleFALSE ): // solid declaration prism : plot::Group3d(top, bottom, tr1, tr2): // final plot plot( prism)
Chapter 2 ( Mathematical graphics with MuPAD
71
Points and polygons are useful not only in geometry. We can use them, for example, to visualize a sequence or any other discrete data. We will talk more about these matters in other chapters. Now, let us look on one very useful example. Suppose that we have a sequence a n "1/2 n . We wish to show how the terms of the sequence behave for large values of n, or in some interval, say n 20. . 30. In this case, we can use the PointList2d or Polygon2d class. Note that, to simplify our declarations, we used the sequence operator. // here we declare our sequence data : [[n,1/(-2)^n] $ n20..30]: // now we declare plot object for the sequence sequence : plot::PointList2d(data, PointSize2*unit::mm, PointColorRGB::Red ): plot(sequence)
72
Getting started with MuPAD y 8.0e-7
6.0e-7
4.0e-7
2.0e-7
0.0e+0 21
22
23
24
25
26
27
28
29
30
x
-2.0e-7
-4.0e-7
Sometimes scattered points are not the best way to illustrate a sequence. We may wish to join the consecutive terms of the sequence. In such cases, we use Polygon2d. Here is our example again, but this time declared as a polygon. sequence2 : plot::Polygon2d(data, PointSize2, PointsVisibleTRUE ): plot(sequence2) y 8.0e-7
6.0e-7
4.0e-7
2.0e-7
0.0e+0 21
22
23
24
25
26
27
28
29
30
x
-2.0e-7
-4.0e-7
Exercise 2.11 1. Write a declaration for a regular hexagon in 2D. Add to your constructions segments joining opposite vertices and points where these segments intersect. Remember, in MuPAD arguments of trigonometric functions should be given in radians. 2. Modify the declaration of a hexagon to obtain a plot of a hexagram in 2D, i.e., a star-like shape with six vertices. 3. Write the declaration for a regular pentagon in 2D.
Chapter 2 ( Mathematical graphics with MuPAD
73
4. Modify the declaration for a regular pentagon in 2D into the declaration of a regular pentagon in 3D. Fill its area with the color red. The pentagon should have an external edge, but should not have any internal edges. 5. Use the regular pentagon from the previous exercise to construct a pentagonal prism. 6. Write down a declaration for a regular pyramid using a square as a base.
2.4.2 Solids in MuPAD In the plot library, we have a number of classes representing solids and some tools for creating new solids. With a single statement we can create each of the following: Box, Cone, Cylinder, Sphere, Dodecahedron, Hexahedron, Icosahedron, Octahedron and Tetrahedron. The declaration of an object representing each of the mentioned classes is very simple. Therefore, we will use this opportunity to learn how we can perform transformations of 3D objects. Let us start with the declarations of four solids: a sphere, a cylinder, a rectangular block (Box) and a cone. The declarations for a sphere, a cylinder and a cone are similar. We start by specifying the radius or radii and then the center or centers of the lower and upper bases. A cylinder requires one radius and two centers. A cone requires two radii and two centers. The declaration of a box is completely different. We use the coordinates of two opposite vertices. // declarations of four solids RedSphere : plot::Sphere(1,[0,0,0], FillColor[1,0,0] ): GreenCylinder : plot::Cylinder(1,[0,0,0],[0,1,1], FillColor[0,0.5,0] ): PinkBox : plot::Box([0,0,0], [1,1,1], FillColor[0.6, 0,0.6] ): BlueCone : plot::Cone(1,[0,0,0], 0.2,[1,1,1]):
74
Getting started with MuPAD
Each of our solids was created in the center of the coordinate system, or touching it. We can plot all of them in one picture. However, overlapping objects are difficult to distinguish. plot(RedSphere, GreenCylinder, BlueCone, PinkBox)
Therefore we move them into new positions. In order to do this, we will use the plot::Translate3d class. The red sphere will be also flattened from two sides using plot::Scale3d class. When using these two classes, we first specify the vector of the transformation and then the object to be transformed, e.g. plot::Translate3d([1,1,1],A). Note, [1,1,1] is the vector of translation but not the point to which we translate our object. // transformations A:plot::Translate3d([1,1,1], plot::Scale3d([0.5,0.5,1],RedSphere) ): B:plot::Translate3d([-1,1,0], plot::Scale3d([0.5,1,1],GreenCylinder) ): C:plot::Translate3d([-1,-1,-1],PinkBox): S:plot::Translate3d([1,-1,0],BlueCone): // finally we plot translated solids
Chapter 2 ( Mathematical graphics with MuPAD
75
plot(A,B,C,S)
In our example, we only mentioned two transformations in 3D. However, the plot library contains the classes representing many other types of transformations. Describing all of them here would take too much time and space in this book. I therefore suggest that readers execute the info(plot) statement and find out what other types of transformations are predefined. Let us explore, instead, some other types of solids available in MuPAD. We will put them inside a transparent cube 4 4 4. Cube : plot::Box([0,0,0],[4,4,4], FillColor[0.7,0.7,1,0.6] ): He : plot::Hexahedron ( Center [2.9,2.9,2.9], Radius 1 ): Te : plot::Tetrahedron ( Center [1,1,3], Radius 1 ): Oc : plot::Octahedron ( Center [1,1,1],
76
Getting started with MuPAD Radius 1
): Ic : plot::Icosahedron ( Center [1, 3, 1], Radius 1 ): Do : plot::Dodecahedron( Center [3, 1, 1], Radius 1 ): Cam : plot::Camera( [28,-23,20],[1.5,1.5,1.5], PI/18 ): plot(Cube, He, Te, Oc, Ic, Do, Cam, AxesNone)
In our example, we could have skipped the parameters for each solid, for example, and used a simple statement such as plot::Icosahedron(). In that case, MuPAD would have created a solid located exactly in the center of the coordinate system.
Chapter 2 ( Mathematical graphics with MuPAD
77
Exercise 2.12 Write the declarations for each of the following constructions. 1. A rectangular block centered at ¡5, 5, 5¢, with two horizontal sides equal to 2 units and a height of 4 units. 2. A cube of eight touching spheres, each with a radius equal to 1 unit. 3. A transparent cylinder circumscribed around a sphere. 4. Three transparent spheres, each with the center at ¡0, 0, 0¢ and radii 1, 2, 3. 5. Use MuPAD help to find what the syntax is for using plot::Rotate3d. Stella Octangula (see the figure below) is a solid obtained from two tetrahedrons. Develop a Stella Octangula using plot::Tetreahedron and plot::Rotate3d.
2.5 Turtle graphics and L-systems In the plot library, there are two classes that are quite unique: plot::Turtle and plot::Lsys. The most important feature of both classes is that they do not use coordinate geometry. Using them we can produce geometric patterns based on line segments.
78
Getting started with MuPAD
2.5.1 A brief introduction to turtle graphics I hazard a guess that not many readers of my book have ever heard about Logo and turtle graphics. In some European countries, Logo is the very first programming language used for teaching computing to students in primary schools and sometimes even in kindergarten. However, turtle graphics or turtle geometry is also considered as a serious scientific discipline with applications in topology, simulation and artificial intelligence. For fans of mathematical recreation, turtle geometry is just another way of creating very interesting patterns. In this section, we will show how one can use turtle graphics to create a few geometric patterns. Turtle geometry does not use coordinates. Imagine that we have control of a creature called a turtle that exists on a plane or on a computer screen. The turtle responds to a few simple commands: forward, turn left, turn right, etc. Our turtle can leave a trace of its path. Depending on how complex its route was, we can get a more or less complex pattern. In the plot library, we have a class called Turtle and we can control Turtle objects using exactly the same commands as those described. The graphical object that we create is the turtle path. It is important to mention that in MuPAD we can create many turtles at the same time and produce a collage of their paths. The syntax for using the turtle is somewhat different from that used for other graphical objects. We start with a statement declaring an empty turtle path, plot::Turtle() or A:plot::Turtle(). Then we give orders to our turtle, for example A::forward(1) or A::right(PI/3). A newly-created turtle always is facing the top edge of the computer screen. In terms of syntax, we have two methods to build the turtle path. In this book I use method 2, listed in the middle column in the table below. It is more convenient for programming, and can be used to create more complex patterns. Here is the table describing all known turtle commands in MuPAD.
Chapter 2 ( Mathematical graphics with MuPAD
79
Method 1
Method 2
What it does
Left(angle)
left(angle)
turn left angle in radians)
Right(angle)
right(angle)
turn right angle in radians
Forward(dist)
forward(dist)
draw a line given length dist
Up
penUp()
pen up and stop drawing
Down
penDown()
pen down and start drawing
Push
push()
save the current position
Pop
pop()
go back to last saved position
LineColor(color) setLineColor(color) change the color of the pen
Let us develop a simple pattern using turtle graphics. T:plot::Turtle(): T::forward(100): T::right(PI/2): T::forward(100): T::right(PI/2): T::forward(50): T::right(PI/2): T::forward(50): T::right(PI/2): T::forward(100): T::right(PI/2): T::forward(25): T::right(PI/2): T::forward(25): T::right(PI/2): T::forward(50): plot(T)
The path that we produced does not look very interesting. However, we can use it to create a more complex patterns. Here are some of them. In the first example, we will rotate T using plot::Rotate2d. All three rotations are performed about the center of a coordinate system with respective angles of =/2, =, and 3=/2.
80
Getting started with MuPAD
Technical comment Turtle graphics does not use coordinates explicitly. However, we can trace any location of the turtle by knowing that a new turtle always starts from the center of coordinate system and it is facing towards the positive direction of the y-axis. T2 : plot::Rotate2d(PI/2,[0,0],T): T3 : plot::Rotate2d(PI,[0,0],T): T4 : plot::Rotate2d(3*PI/2,[0,0],T): plot(T,T2,T3,T4)
We will obtain another interesting pattern by translating T to another place and then rotating it. The enclosed code also shows another interesting feature of MuPAD graphics—we can change some parameters of the graph globally by inserting them into the final plot statement. A1 : plot::Translate2d([50,-75], T): A2 : plot::Rotate2d( PI/4,[0,0],A1): A3 : plot::Rotate2d(2*PI/4,[0,0],A1): A4 : plot::Rotate2d(3*PI/4,[0,0],A1): A5 : plot::Rotate2d(4*PI/4,[0,0],A1): A6 : plot::Rotate2d(5*PI/4,[0,0],A1): A7 : plot::Rotate2d(6*PI/4,[0,0],A1): A8 : plot::Rotate2d(7*PI/4,[0,0],A1): plot(A1,A2,A3,A4,A5,A6,A7,A8, LineColorRGB::Red, LineWidth0.5 )
Chapter 2 ( Mathematical graphics with MuPAD
81
Our experiments with the turtle and transformations are a good opportunity to mention another important operation available in the plot library, which is plot::modify. We use it to make a copy of an existing object and modify some of its parameters. In the next example, I create four copies of T and then plot each of one using a different line width and color. Observe that we can put some parameters into the modify statement as well as into the final plot statement. Parameters declared in the final plot statement will be applied to all objects that use only the default values of parameters. Here is our example. A1 : plot::modify(T, LineColorRGB::Red): A1 : plot::Translate2d([50,-75], A1): A3 : plot::modify(T, LineColorRGB::Blue, LineWidth2): A3 : plot::Translate2d([50,-75], A3): A3 : plot::Rotate2d(2*PI/4,[0,0],A3): A5 : plot::modify(T, LineColorRGB::Green, LineStyleDashed, LineWidth0.5 ): A5 : plot::Translate2d([50,-75], A5): A5 : plot::Rotate2d(4*PI/4,[0,0],A5): A7 : plot::modify(T, LineColorRGB::Brown): A7 : plot::Translate2d([50,-75], A7): A7 : plot::Rotate2d(6*PI/4,[0,0],A7): plot(A1,A3,A5,A7, LineWidth0.75)
82
Getting started with MuPAD
In a short chapter, it is impossible to describe in detail the syntax and all properties of MuPAD graphical objects and list all operations that can be performed on them. I therefore suggest to the readers to experiment with our examples, change the code as often as needed, and follow their imagination and contemplate the results. This is the best way to gain knowledge about MuPAD graphics. While introducing turtle commands, I mentioned two methods of giving orders to a turtle. Below I show two short examples demonstrating both methods and the essential differences between them. Method 1
A : plot::Turtle( Forward(1), Right(PI/2), Forward(1) ): plot(A) Method 2
A : plot::Turtle(): A::forward(1): A::right(PI/2): A::forward(1): plot(A) At first sight, the difference between the two methods seems minor. However, once we begin to learn about programming later in the book, we will see the advantages of the second method. Exercise 2.13
Use the turtle graphics to produce:
1. A square with a side 1 unit long. 2. A hexagon with each side 2 units long. 3. A hexagram with each side 4 units long.
Chapter 2 ( Mathematical graphics with MuPAD
83
4. A tiling pattern using hexagons (four rows and four columns). 5. A tiling pattern using octagons and squares (four rows and four columns).
2.5 5.2 2 Lindenmayer systems After this short section about turtle graphics we can move to another group of mathematical objects, which are called Lindenmayer systems or L-systems, for short. L-systems have their origins in biology and in particular in the processes of growing plants and other living creatures. Their creators are Aristid Lindemayer and Przemysáaw Prusinkiewicz, Polish by birth. The beautiful books about L-systems are a great inspirational source not only for biologists or mathematicians, but also for mathematically inclined artists. In order to understand how an L-system is created, we will analyze a very simple example that is well-known as a Koch curve or Koch snowflake. In order to make things even simpler, we will analyze only one part of it (fig.2.4).
a0
a1
a2
a3
a4
Fig. 2.4 Development of the Koch curve Let us start with a single segment, a, say 1 unit long (fig. 2.4 left). We
84
Getting started with MuPAD
divide it into three equal parts, attach an equilateral triangle to its central part, pointing to the right, with a side length of 1/3 of the segment. Finally, we will remove the base of the triangle. This will create the figure a1. Now, by applying the same process to the segments of the resulting figure, we obtain figures a2, a3, a4. We can continue this process with as many steps as we wish, thus producing more and more complex objects. There is, of course, no end to this creation. However, we can imagine how the resulting figure would look if we could continue our activity infinitely many steps. It is time to introduce some required terminology. The starting figure, in our case this is the segment a, will be called the seed. The rule for creating new figures will be called the iteration rule. The sequence of figures obtained will be called an orbit. The final result, the one that we could obtain after infinitely many steps, is usually called a fractal—in our example it is the fractal known as the Koch curve, or at least part of it. It is very convenient to use the term generations in respect to the obtained figures. For example, a should be considered as generation zero, a1 as the first generation, a2 as the second generations, and so on. In MuPAD, L-systems are implemented with the use of turtle graphics. Therefore, as one can imagine, we must supply the turtle with information about the seed, the iteration rule and how many times the turtle has to apply the rule. In other words, how many generations should be produced. Here is the MuPAD code for the fourth generation of the Koch curve. I formatted this code in such a way that I can add a comment to each parameter. KochCurve : plot::Lsys( // start a new L-system PI/3, // turtle must always turn PI/3 "FFF", // this is the seed "F""F-FF-F", // iteration rule Generations4 // number of generations ): plot(KochCurve) // now plot the turtle path
Chapter 2 ( Mathematical graphics with MuPAD
85
I guess, now my readers are anxious to know what the meaning is of the symbols ‘’ and ‘-’ in the L-system declaration. Let us look at all parameters we use to declare our L-system. 1. The expression Lsys is the name of the class used to declare an L-system. 2. The number PI/3 is the angle that the turtle may turn. Note that our turtle has lost some of its freedom. It can always turn only the same given angle. Angles, as always in MuPAD statements, should be declared in radians. 3. The expression "FFF" is our seed. The character F means a single segment of length 1, the symbol ‘’ means turn right, and the symbol ‘-’ means turn left the declared angle, in our example PI/3. 4. The expression "F""F-FF-F" defines the iteration rule. According to it, each segment F is replaced by the turtle path F-FF-F. 5. The parameter Generations7 defines the number of iterations. Here is the complete list of symbols we can use to declare L-systems in MuPAD: F means go
forward 1 step, or one unit, and draw
f means go
forward one step without drawing a line
86
Getting started with MuPAD means turn left - means turn [ save ] go
the given angle
right the given angle
the current position (branching symbol)
back to the last saved position (branching symbol)
While declaring an L-system, we can also declare our own symbols. For example, "S"Line declares a new type of segment. Having declared two or more types of segments, we can create a separate rule for each of them. We can declare a color symbol, for example "B"RGB::Brown. In this way, we will be able to change the color of the pen while developing an L-system. Let us explore a few examples of L-systems created by simple modifications of the Koch curve. Koch1 : plot::Lsys(PI/2, "F-F-F-F", "F""FF-F–F-F", Generations4 ): plot(Koch1)
Koch2 : plot::Lsys(PI/2, "FFFF", "F""FF-F-FFFF", Generations4 ): plot(Koch2)
Chapter 2 ( Mathematical graphics with MuPAD
87
Finally, let us see a more complex example using multiple colors and branching symbols. weed : plot::Lsys(PI/5, "F", "F""BR[FHF][-FHF]FHF", "R""BRR", "R"Line, "B"RGB::Brown, "H"RGB::ForestGreen, Generations5 ): plot(weed)
This was the last example showing the beauty of L-systems. However, readers can find more about L-systems by doing the following exercises.
88
Getting started with MuPAD
Exercise 2.13 1. While creating a Koch curve, the seed was created by turning the turtle twice to the left and each time 120 degrees. What will happen if we draw the seed in the opposite direction, i.e. turning each time right 120 degrees? 2. Develop an L-system with the seed "F", angle =/2, and the iteration rule "F""-FF-F-FF". What shapes we will get in the second, third and fifth generations? 3. Use the rule "F""FF-FF-FF" to draw by hand the first generation produced from a single segment. Use this rule and square as a seed to produce a fourth generation L-system. In fact, you can obtain two different L-systems shown in the figure below. How this is possible?
Fig. 2.5 Two modifications of the Koch curve, generation4.
Chapter 2 ( Mathematical graphics with MuPAD
89
2.6 6 Animation step-b by-s step There are many topics in mathematics that cannot be illustrated without animation and many others that gain a lot by using animation. In MuPAD, we can animate any plot object and any of its features. However, even if something is moving, that does not mean it is useful. We have to be sure that our animation explains something important. In this section, we will develop a number of animations and show, step by step, how to create animated mathematical graphs and explain what we can gain from doing so. Let us start with a very basic problem. We have a curve given by the following parametric equations: x t 2 " 4 and y t/2. We would like to find out how the parameter t flows through the graph. In other words, if a particle is moving along this curve and its coordinates are t 2 " 4, t/2 , where will the particle start, where will it finish, and what will be its traveling speed? In order to solve this problem, it is useful to think of the particle as a point traveling along a curve and see its movement in the animation. We need to create two plot objects: one is the curve and the other is the point representing the particle. Since the point should move, we specify the following: Particle : plot::Point2d([a^2-4, a/2], a-3..3): We also know that the coordinates of the moving point coincide with the coordinates of the points on the curve and that its locations can be calculated by running through the values a-3..3. In this book, whenever it is possible, we use the letter a as the name for the animation parameter. However, we could use any other valid variable name. Let us now write out the complete code and check what we get. Curve : plot::Curve2d([t^2-4, t/2], t-3..3): Particle : plot::Point2d([a^2-4, a/2], a-3..3): plot(Curve, Particle)
90
Getting started with MuPAD
y 1.4 1.2 1.0 0.8 0.6 0.4 0.2 -4
-3
-2
-1
-0.2
1
2
3
4
5
x
-0.4 -0.6 -0.8 -1.0 -1.2 -1.4
The small point on the right of the bottom of the curve indicates the starting position of the particle. The rest we can see when we open the picture with the Virtual Camera—right click on the picture and Graphics ObjectOpen. We can see that the Virtual Camera has a new toolbar that looks just like the control box in the Windows Media Player, WinAmp, or any other computer sound or video application. The animation control box in the Virtual Camera, starting from the left, contains the following tools: a button to move the playhead to the beginning of the animation, a button to start playing the animation, a slider to move along the animation timeline, a button to go the end of the animation, a button for continuous play of the animation, and a setup button to control the speed of the animation. We can play our animation by pressing the start button. As we can see, the movement of the particle is fastest along the branches of the curve and slows down near the point "4, 0 . We can make a number of improvements in our example: change the size of the particle, its color, etc. However, sometimes we want to create such an animation to simulate that the particle moves and leaves a trace of its movement. This simply means that we have to draw the curve from its
Chapter 2 ( Mathematical graphics with MuPAD
91
starting point (t-3) to the current position of the particle. This requires us to change the way the curve is declared. The range of the variable t must be from -3 to a, where a is the same animation parameter that we used when declaring the particle. Curve : plot::Curve2d([t^2-4,t/2], t-3..a, a-3..3): Here is the final code for our particle animation. Curve : plot::Curve2d([t^2-4, t/2], t-3..a, a-3..3): Particle : plot::Point2d([a^2-4, a/2], a-3..3, PointSize2, PointColorRGB::Red ): plot(Curve, Particle) y 1.4 1.2 1.0 0.8 0.6 0.4 0.2 -4
-3
-2
-1
-0.2
1
2
3
4
5
x
-0.4 -0.6 -0.8 -1.0 -1.2 -1.4
The obtained animation reminds me of the route of a comet passing near the solar system. Now, we could add the sun and a few planets to create the complete model of a solar system with a comet. I will leave this to the readers of this book. Meanwhile, let us move on to another example of an animation. In school mathematics, there are many examples of functions where we have to determine the shape of the graph of a function depending on some of its parameters. For example, we may need to find out how the value of a affects the graph specified by the equation y ax " h 2 k. We can illustrate this point using a very simple animation. We assign values
92
Getting started with MuPAD
to the two remaining parameters h and k, and treat a as an animation parameter. Here is the code for this example. h : 1: k : 1: Parabola : plot::Function2d( a*(x-h)^2k, x-1..3, a-2..2 ): plot(Parabola) y 8 6 4 2
-1.0
-0.5
0.5
1.0
1.5
2.0
2.5
3.0
x
-2 -4 -6
Until now, our sample animations were simple and some readers might be a little disappointed. Therefore, let us develop a more complicated example of an animation. Suppose that we have two circles, one with the radius r and another with the radius R, such that 0 r t R, for example r 0. 5 and R 2. The smaller circle rolls without slipping inside the larger circle. If we mark a particle on the edge of the small circle and trace its path we will produce a closed plane curve known as an hypocycloid. Below I enclose the complete code for this example. // radii of both circles r : 0.5: R : 2: // coordinates of the particle coordinates : [(R-r)*cos(phi)r*cos(((R-r)/r)*phi), (R-r)*sin(phi)-r*sin(((R-r)/r)*phi)]: // static objects LargeCircle : plot::Circle2d(R, LineColorRGB::Black
Chapter 2 ( Mathematical graphics with MuPAD ): // objects to animate SmallCircle: plot::Circle2d( r, [(R-r)*cos(a), (R-r)*sin(a)], a0..2*PI, Color [0.8,0,0], LineColorRGB::Black, LineWidth0.1, FilledTRUE, FillPatternSolid ): Particle:plot::Point2d( coordinates, phi 0..2*PI, PointSize 2, PointColor [0,0,1] ): Curve : plot::Curve2d( coordinates, phi 0..a, a0..2*PI ): // now we plot all together plot(LargeCircle, SmallCircle, Particle, Curve, Frames80, ScalingConstrained, AxesInFrontTRUE ) y
2
1
-2
-1
1
-1
-2
2
x
93
94
Getting started with MuPAD
I suggest that readers type out the complete code in a MuPAD notebook and execute it. Observe that by changing the initial values for r and R, we may obtain a completely new curve. Therefore, a number of interesting animations can be created. Note also that for some lengths or radii, the curve might not be closed. In this case, we will have to roll the small circle several times along the same path. Which values must be adjusted to roll the small circle two or more times inside the large circle? Exercise 2.14 1. Develop animations showing how the graph of the function y a sinbx c changes, depending on each of parameters a, b and c. Hint: we can animate one parameter at a time. Therefore, the other two parameters should have constant values. 2. The path of a projectile in the air can be described by the parametric equations x tv 0 cos ), y tv 0 sin ) " gt 2 /2, where v 0 is its initial velocity, ) is the angle of the projectile path at its the starting point with the horizontal axis and g is the gravity (about 32). Develop an animation simulating the movement of the projectile. Experiment with different values of ) and v 0 . When do we get the largest range of the projectile? Finally check what happens if we use a different gravity. 3. The path traced by a given point on the circumference of a circle that rolls along a line is called a cycloid. Develop an animation showing the path of the point. The parametric equations of the cycloid are as follows: x r) " sin ) and y r1 " cos ) , where r is the radius of the circle and ) is the angle that the circle has been rolled.
Introduction to calculus of one variable In the two previous chapters, we learned some of the basic elements of MuPAD and we explored in detail the features of MuPAD graphics. In doing so, we built the foundation for the detailed study of different mathematical disciplines. In this chapter, we will learn some basic applications of MuPAD in the calculus of functions of one variable. Calculus itself is a wonderful discipline with many interesting topics. A complete course of calculus with MuPAD would take thousands of pages. Unfortunately, due to scope of this book and limited space, we will merely scatch the surface of this rich subject, leaving more a detailed investigation for another time.
2.1 1 Declaring functions of one variable In the previous chapter we introduced some simple declarations of functions. Now it is time to extend this knowledge. We already know that the declaration of a function requires the syntax F : x-f(x), where F is the name of the function, x is the variable used in the function formula, and f(x) is a formula for the function. Here is an example of the declaration of a function. g : x - (x^3x^2x1)/(x^2x1)
96
Getting started with MuPAD
x3 x2 x 1 x2 x 1 Observe that using this syntax, we can declare functions that go much beyond what we have done before: g : x - nextprime(floor(x)): g(21.98) 23 We have declared a function that, for a given x, produces the smallest prime number larger than x. A function like this can be also plotted using the syntax that we have already learned in the chapter on graphics. G : plot::Function2d(g(x), x0..10, XSubmesh10): plot(G) y
11 10 9 8 7 6 5 4 3 2 0
1
2
3
4
5
6
7
8
9
10
x
In this example, we used the function floor(x), a function very useful in calculus. There is another function, ceil(x), which plays a similar role. The first of these functions produces the largest integer smaller than x. The second produces the smallest integer larger than x. In mathematics, we denote these functions by HxI and FxG respectively. The graph of each of these functions contains a sequence of horizontal segments with jumps connecting them, like a set of stair steps. For this reason, these functions are often called step functions. Here is a graph of the function HxI. F : plot::Function2d(floor(x), x-5..5): plot(F)
Chapter 3 ( Introduction to calculus of one variable y
97
4 3 2 1
-5
-4
-3
-2
-1
1
2
3
4
-1
5
x
-2 -3 -4 -5
The step functions play a significant role in the investigation of the limits and continuity of functions. Below, I show another example, a so-called sawtooth function, produced with the use of the floor function. H : plot::Function2d(x-floor(x), x-4..4): plot(H, ScalingConstrained) y
1.0 0.5
-4
-3
-2
-1
0
1
2
3
4
x
Let us return for a while to prime numbers, another example of a function of one variable. This time, we calculate the difference between two consecutive prime numbers. A function like this contains only discrete values, and for this reason should be considered as a sequence. Observe also that our declaration makes sense only for n 2. g : n - ithprime(n)-ithprime(n-1): g(25) 8 g(2567) 6 In general, in this book we treats sequences as functions of one variable with integer arguments. This allows us to apply some of the methods that we use for functions with real numbers as arguments.
98
Getting started with MuPAD
The next example is even more unusual. This time, our function produces a list of powers 2 n , where n 1. . HxI. f : x - [ 2^n $ n1..floor(x)]: f(12) [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096] In a very similar way, we can declare functions of one variable that produce lists of lists, matrices, sets and many other interesting mathematical objects. These functions will be useful in other parts of this book. However, in this chapter we will concentrate on functions of one variable with real number values. In the first chapter of this book, we introduced some functions build from pieces of other functions, so-called piecewise functions. Such functions play a significant role in many areas of mathematics, including calculus. We declare piecewise functions using the keyword piecewise. Here I show an example of a function that will take the value 1 for x ¡0, 1¢ and 0 outside. CharInt01 : x - piecewise([x0,0],[x1,1],[x1,0]): While declaring this function, we used a sequence of pairs [condition, value], where condition describes a subset of real numbers and value is the value of the function on this subset. There are no restrictions on the order of terms in the definition of a piecewise function. The subsets defined by conditions can also overlap. However, we have to be aware that the wrong order of terms and overlapping subsets can lead to errors. Let us analyze an example of a piecewise function with overlapping subsets. We will produce two functions with identical terms, overlapping subsets, and a different order of terms. F1 : x - piecewise([x 1, 2], [x-1, 1]): F2 : x - piecewise([x-1, 1], [x 1, 2]): Now, let us plot these functions and compare the obtained graphs. plotfunc2d(F1(x), x-3..3, YRange0..2)
Chapter 3 ( Introduction to calculus of one variable
y
99
2.0
1.5
1.0
0.5
-3
-2
-1
0
1
2
3
x
plotfunc2d(F2(x), x-3..3, YRange0..2) y
2.0
1.5
1.0
0.5
-3
-2
-1
0
1
2
3
x
From the above graphs it is easy to work out how MuPAD plots a piecewise function fx . For any given x from the domain of the function, MuPAD checks consecutive conditions starting from the first one on the left. If a condition is true, then MuPAD produces the value fx and stops checking the remaining conditions, otherwise the next condition is checked. Therefore, while declaring a piecewise function, we should place conditions in the order we want them to be checked and, if possible, avoid using overlapping subsets. It can be very helpful to use the logical connectors or, and, and not while building piecewise function conditions. The above CharInt01(x) function can be reformulated in a form where we do not have any doubts about how it will be calculated. CharInt01 : x - piecewise( [x 0 or x 1, 0], [x 1 and x 0, 1] ) We finish our investigations of piecewise functions with another example. Here is a graph of a piecewise function. The function is defined only for 0 t x t 2 and x 3.
100
Getting started with MuPAD
y
1 0.8 0.6 0.4 0.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
2.2
2.4
2.6
2.8
3
x
Here is one of the possible declarations of this function. H : [x [x [x )
x - piecewise( 0 and x 1, sqrt(1-x^2)], 1 and x 2, 1], 3, 1]
For any x from the domain of the function Hx , it returns the right value and UNDEFINED if x does not belong to the domain of the function. However, there is still one obstacle—the graph of the function does not show a value for x 2 or x 3. This leads us to a more careful analysis of how MuPAD plots graphs of functions. Exercise 3.1 Type in the declarations of the following functions. Use the declarations to calculate selected values of functions. 4x 7 x " 1 x 1 2. gx x3 1 x " 9x 1. fx
3. hx
9"x x"6
1 " sin x 1 cos x x 5. lx 2 x "1 sin 3x 6. mx 1 cos 3x 4. kx
Chapter 3 ( Introduction to calculus of one variable
101
"5 for x "5 7. wx
x
for "5 t x t 5
5
for x 5
x 2 for x t 1 8. ux
x 3 for |x| 1 2x for x u 1
9. vx
x
for x t 1
"x 2
for 1 x 2
x
for x u 2
3.2 2 How does MuPAD plot graphs of functions? We know a lot about MuPAD plots. Let us now consider some specific cases and see what happens with our plot. It is important to understand what may go wrong with the plots and why. Let us consider the function y sin120=x . We already have some idea what the plot may look like—it is the sine function, with its argument multiplied by 120=. The resulting plot should be a graph of the sine function squeezed horizontally. We will produce three different plots of this function, using a different range for x each time. Here they are. Y:plot::Function2d(sin(120*PI*x), x-1..1): plot(Y) -1.0
-0.8
-0.6
-0.4
-0.2
y
x 0.2
0.4
0.6
The resulting graph is nonsense. Let us try again.
0.8
1.0
102
Getting started with MuPAD
Y2 : plot::Function2d(sin(120*PI*x), x-1/2..1/2): plot(Y2) y
2.0e-16
1.0e-16
-0.5
-0.4
-0.3
-0.2
-0.1
0.1
0.2
0.3
0.4
0.5
x
-1.0e-16
-2.0e-16
This time we are closer to what we expect, but the graph is still wrong. Here is one more attempt. Y3 : plot::Function2d(sin(120*PI*x), x-1/30..1/30): plot(Y3) y
1.0 0.8 0.6 0.4 0.2
-0.03
-0.02
-0.01
0.01 -0.2
0.02
0.03
x
-0.4 -0.6 -0.8 -1.0
Finally we got the right plot. However, we still need to find out what went wrong with first two. MuPAD, while plotting the graph of a function, divides the range of the variable x into 120 equal intervals, calculates the values of the function for the endpoints of intervals and plots the graph by connecting these values. It may happen, as in our example, that the function changes significantly inside of an interval. In such cases, none of the changes of functions inside the interval are shown on the graph.
Chapter 3 ( Introduction to calculus of one variable
103
Therefore, in order to capture these changes, we must use sufficiently small intervals. We did this by narrowing the whole range from ¡"1, 1¢ to ¡"1/2, 1/2¢ and finally to ¡"1/30, 1/30¢. We could do this another way. This would require us to use a denser division of the range for the variable x. However, in our example, we still may not get the correct graph. Can you explain why? Here are two more attempts. Y : plot::Function2d(sin(120*PI*x), x-1..1, XMesh242 ): plot(Y) y
1.0 0.8 0.6 0.4 0.2
-1.0
-0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
1.0
-0.2
x
-0.4 -0.6 -0.8 -1.0
Y : plot::Function2d(sin(120*PI*x), x-1..1, XMesh1001 ): plot(Y) y
1.0 0.8 0.6 0.4 0.2
-1.0
-0.8
-0.6
-0.4
-0.2
0.2 -0.2 -0.4 -0.6 -0.8 -1.0
0.4
0.6
0.8
1.0
x
104
Getting started with MuPAD
We used the XMesh parameter here to get a denser mesh. However, the function has too many jumps for the plot to capture. Therefore, in this and similar examples, narrowing the range of the function may be important. The way graphs are plotted does not allow us to plot isolated points of functions or to distinguish whether the end of a plot segment belongs to the graph or not. Another important feature of MuPAD is the ability to check for discontinuities of a function. We know a number of functions that have infinite vertical jumps. MuPAD can detect them and draw vertical asymptotes if they exist. Let us consider the example of a function with an infinite jump. g : x - (x^3x^2x1)/(x^2-1): plotfunc2d(g(x), x0..2) y
30
20
10
0 0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
x
-10
-20
-30
The same example, plotted with additional parameter DiscontinuitySearchFALSE, will produce the wrong graph. The discontinuity search option can be easily turned off and on in Virtual Camera. g : x - (x^3x^2x1)/(x^2-1): plotfunc2d(g(x), x0..2,DiscontinuitySearchFALSE)
Chapter 3 ( Introduction to calculus of one variable
y
105
30
20
10
0 0.2
0.4
0.6
0.8
1.0
1.2
1.4
1.6
1.8
2.0
x
-10
-20
Exercise 3.2 1. Obtain the graphs of the functions from example 3.1. 2. Obtain the graphs of the following functions. Find the best way to produce graphs that are as accurate as possible. a. y
sin 30x 1cos 30x
b. y
cosx 5 x
c. y sin1/x d. y sin 120=x 0. 01 sin 1200=x e. y signsin1/x . Note that the signx function produces 1 for x 0, "1 for x 0 and 0 for x 0. In MuPAD use the keyword sign.
3.3 3 Limits The limit procedure that we learned in the chapter 1 is quite universal. We can use it to obtain the limits of functions of one or more variables as well as the limits of sequences. Let us remind ourselves how to use it. limit(x^33*x-1, x1)
3 Sometimes it is more convenient to declare the function first and then use its name. f : x - (x^2-3*x-1)/(1-x)
106
Getting started with MuPAD
2 x v x "3x"1 1"x
Now, when we are sure that we typed in the formula of the function correctly, we can use it to produce the limit of the function for a given x. limit(f(x), x5)
" 94 This was quite simple. What about limits when, x o.? limit(f(x), xinfinity)
". limit(f(x),x-infinity)
. Note that if we type the infinity symbol . as infinity, and it means .. We can tell that from looking at the formula of the above function we can expect to have some problems at x 1. Therefore, let us try to find the limit of fx for x 1. limit(f(x), x1) undefined This is just what we expected. Let us try to find the limits for x 1 from the left and right sides. limit(f(x), x1, Right)
. limit(f(x), x1, Left)
". 2 Now, we know for sure that the limit of the function fx x "3x"1 does
1"x
not exist for x 1 since the left limit is "., whereas the right limit is .. In the same way we can investigate the limits of many other functions. limit(1/x, x0, Right)
.
Chapter 3 ( Introduction to calculus of one variable
107
limit(1/x, x0, Left)
". limit(sin(1/x), x0) undefined limit(x*sin(1/x), x0) 0 limit(sign(x), x0) undefined limit(sign(x), x0, Right) 1 limit(sign(x), x0, Left)
"1 It is slightly more difficult to find the limits of piecewise functions. Here we may expect problems with points that are on the border of two neighboring segments. Let us see how MuPAD calculates the limits a continuos piecewise function. H : x - piecewise( [x -1 or x 1, x^2], [x 1 and x -1, 1] ): The graph of the function shows that we should be able to find the limits for x 1 and x "1. plotfunc2d(H(x), x-2..2, YRange0..2) y
2.0
1.5
1.0
0.5
-2.0
-1.5
-1.0
-0.5
0.0
0.5
1.0
1.5
2.0
x
108
Getting started with MuPAD
At the same time, while trying to obtain one of the limits we get, limit(H(x), x1)
lim xv1
x 2 if 1 t x 1 if 0 t x
However, the left and right limits produce the expected results. limit(H(x), x1, Right) 1 limit(H(x), x1, Left) 0 Observe, there are still some functions for which MuPAD is unable to calculate some limits. Here is one such example. limit(floor(x), x2)
limHxI xv2
limit(floor(x), x2, Left)
lim HxI
xv2 "
limit(floor(x), x2, Right)
lim HxI
xv2
Limits of sequences are calculated in exactly the same way as limits of other functions. Here are some examples of the limits of sequences. an : n - (1-1/n)
n v 1"
1 n
limit(an(n), ninfinity) 1 bn : n - (1-1/n)^n
n v 1 "
1 n
n
limit(bn(n), ninfinity)
e "1
Chapter 3 ( Introduction to calculus of one variable
109
cn : n - (sin(1/n))^2(cos(1/n))^2 2
n v sin 1n cos 1n
2
limit(cn(n), ninfinity) 1 dn : n - (3^(2*n1))^(1/n)
nv
n
3 2n1
limit(dn(n), ninfinity) 9 Note that we treat sequences as functions on integers. However, MuPAD does not do the same while calculating their limits. Therefore, in many examples, the results produced by MuPAD are wrong. Let us analyze one such example. a : n - sin(n*PI)
n v sin= n It is obvious that we have here a sequence of zeros. a(n) $ n1..20 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 Therefore, we would expect MuPAD to produce lim a n 0. Here is what nv.
we get, limit(a(n), ninfinity) undefined Exercise 3.3 1. In problems a through d, evaluate the required limits and verify them using graphs. a. lim xv3
1/x"1/3 x"3
b. lim xv9
3" x 9"x
c. lim xv0 d. lim xv0
1x " 1"x x x"sin x x3
110
Getting started with MuPAD
2. Declare the function f : x v sin x sin1/x . Use a MuPAD plot to show that the graph of the function is squeezed between the functions sin x and " sin x. How does this influence the limit lim xv0 fx ? 3. MuPAD is not able to calculate the limit of the function x HxI for x 0. Plot a very accurate graph of the function and use it to obtain the limit lim xv0 x HxI.
3.4 4 The derivative Calculating derivatives in MuPAD is straightforward. We need to know the diff procedure or alternatively use the "’" operator to calculate a derivative of almost any function. However, the derivative is good starting point for many interesting investigations. Therefore, it is worthwhile to spend some time on this topic and find out what MuPAD can do for us. For a start, let us define a simple function. f : x - x^3 3*x^2 5*x^(-3)
x v x3 3 x2
5 x3
Now we can ask MuPAD to calculate some selected derivatives of fx . Here they are. diff(f(x),x)
6 x 3 x2 "
15 x4
or, alternatively, f’(x)
6 x 3 x2 "
15 x4
diff(f(x),x,x)
6x
60 x5
6
Observe that diff(f(x),x,x) is a convenient shortcut for diff(diff(f(x),x),x)
6x
60 x5
6
Chapter 3 ( Introduction to calculus of one variable
111
In exactly the same way, MuPAD will calculate the derivative of any given order, for example for n 10. diff(f(x), x,x,x,x,x,x,x,x,x,x)
1197504000 x 13 Typing in 10 or more x can be a bit tiring and can lead to some errors. Therefore, it is worthwhile to recall the sequence operator $. Instead of typing x ten times, we can use a construction like x $ 10. This is much simpler, and the result of the differentiation is still the same. diff(f(x), x $ 10)
1197504000 x 13 We can use MuPAD plots to display on the same coordinate system both the function and its derivative, and then analyze the dependencies between them. Below, I will show an example of such a plot. We start with a declaration of the function fx 3x 4 " 11x 2 " 5x " 5 and a rough plot of fx and f U x . Here are our declarations and below is the obtained plot. f : x - 3*x^4-11*x^2-5*x-5: F1 : plot::Function2d(f(x)): F2 : plot::Function2d(f’(x)): plot(F1,F2) y
1600 1400 1200 1000 800 600 400 200
-5
-4
-3
-2
-1
-200
1
2
3
4
5
x
-400 -600 -800 -1000 -1200 -1400
We can easily tell from the obtained plot that the most interesting part of the graph is for "2. 5 t x t 2. 5. We are not able to say anything about the range for the variable y. Therefore, we will try "25 t y t 25. If this range
112
Getting started with MuPAD
is not enough or too much, we can always adjust it. We would like to be able to distinguish on the graph between fx and f U x . We therefore use the plot::Function2d class with a thick line for fx . f : x - 3*x^4-11*x^2-5*x-5: F1 : plot::Function2d(f(x), LineWidth0.6): F2 : plot::Function2d(f’(x)): plot(F1,F2,ViewingBox[-2.5..2.5,-25..25]) y 20
10
-2.5
-2.0
-1.5
-1.0
-0.5
0.5
1.0
1.5
2.0
2.5
x
-10
-20
The obtained plot meets our needs quite well. However, it would be much better to have a grid on the graph, similar to a plot on graph paper, an explantory legend, and perhaps a few other things that would make the graph more useful. In the graphics chapter we learned how to add these elements using the Virtual Camera. Here we will use the selected parameters to enhance our plot. The names of these parameters can be easily found by exploring the Objects browser and Properties panels in the Virtual Camera. Here is our code with some comments. f : x - 3*x^4-11*x^2-5*x-5: F1 : plot::Function2d(f(x), LineWidth0.8, LegendText"Function f(x)" ): F2 : plot::Function2d(f’(x), LineColor[0,0,0], LegendText"Derivative f’(x)" ): plot(F1,F2,
Chapter 3 ( Introduction to calculus of one variable
113
ViewingBox[-2.5..2.5,-25..25], // parameters to show the grid XGridVisibleTRUE, YGridVisibleTRUE, XSubgridVisibleTRUE, YSubgridVisibleTRUE, // parameters to define density of the grid XTicksDistance1, YTicksDistance10, XTicksBetween9, YTicksBetween3, // show the legend LegendVisibleTRUE, plot::Canvas::BorderWidth0.5, // add the title on the canvas plot::Canvas::Header"Function f(x) and its derivative" )
Function f(x) and its derivative y 20
10
-2
-1
1
2
x
-10
-20 Function f(x) Derivative f'(x)
The obtained plot shows exactly what we wanted—the function and its derivative. Now we can use it to draw some conclusions. From calculus we know that the values of x where f U x 0 are potential places where the function may have critical points—local minimum or maximum or inflection points. The graph that we produced can be used to
114
Getting started with MuPAD
locate such points and identify their character, provided that the graph is absolutely correct. Therefore, analyzing the graph we can conclude that fx has a local minimum for "1. 3 x "1. 2 and another one for 1. 4 x 1. 5. Moreover for "0. 3 x "0. 2, the function has a local maximum. Observe that in each of these points, the derivative of the function changes sign. This confirms that our conclusions are correct. Exercise 3.4 In problems 1 to 5, plot the graph of the function and its derivative. Use the graph to identify approximate locations of critical points. 1. y x 3 " 3x 2 " 5x 2. y x 5 " 5x 3 5x " 1 3. y x 4 " 3x 2 " 1 4. y
1x 2 1"x 2
5. y x 3 /3 " 2x
3.5 5 Curve-s sketching with MuPAD In calculus, curve-sketching is an important activity. It allows us to obtain detailed information about a function and its graph. The traditional approach requires us to follow rigidly a sequence of steps that are listed in any calculus textbook. With a computer algebra system such as MuPAD, we can simplify this work and get very accurate results in shorter time. First, let us observe that in MuPAD, we complete tasks with the use of a few simple commands that normally require many hours. One such time-consuming activity was drawing the proper graph of a function. With MuPAD we can, in some sense, work backwards. First, we plot the graph and roughly identify all the critical points, asymptotes and other elements. Then we verify our findings by precise calculations. Finally, we plot again a very accurate graph with all the elements that we found. Here is an example taken from a calculus textbook. We will show step by step how we can obtain a qualitatively accurate graph with MuPAD. Let us start by declaring the function fx
3x 3 in MuPAD. Then we 9x 2 "25
Chapter 3 ( Introduction to calculus of one variable
115
construct its rough graph. f : x - 3*x^3/(9*x^2-25)
xv
3 x3 9 x 2 " 25
plotfunc2d(f(x), x-10..10) y 3
2
1
-10
-8
-6
-4
-2
2
4
6
8
10
x
-1
-2
-3
The graphs shows that fx may have: 1. One point of intersection with the x-axis near x 0, 2. One local minimum near x 2. 5, one local maximum near x "2. 2, and an inflection point near x 0, 3. Two vertical asymptotes somewhere near x 1. 8 and x " 1. 8, 4. Probably one slant asymptote y ax. With this knowledge, we can start calculating and check our hypotheses. We will start by calculating the zeros of the function. solve(f(x)0, x)
£0¤ This confirms that fx has only one intersection point with the x-axis and it is x 0. Now we calculate the first derivative of the function and everything that is related to it. In our calculations, we denote f U x by gx . g: x - diff(f(x), x)
xv
x
fx
116
Getting started with MuPAD
g(x)
54 x 4 9 x2 " 2 9 x " 25 9 x 2 " 25 2 This allow us to calculate the roots of the equation f U x 0. solve(g(x)0, x), float(solve(g(x)0, x))
0, "
5 3 5 3 , 3 3
, £"2. 886751346, 0. 0, 2. 886751346¤
Technical comment In some situations, like the one above, it is convenient to obtain in the same line the results of two or more calculations. We achieve this by separating two or more commands by commas. In our example, we obtained the exact results and their decimal approximations. However, the situation described here is exceptional and in general we should avoid the placing two or more commands on the same input line since this type of code is harder to read. From a technical point of view, the comma cannot be used to separate two commands as we did with ":" and ";". The comma that we used here produces a sequence of results and we can apply it only when this makes a sense, in other words, when creating a sequence is possible. Let us use the obtained results to produce the values of the function for these arguments. f(-5*sqrt(3)/3), float(f(-5*sqrt(3)/3))
"
5 3 , "1. 443375673 6
f(5*sqrt(3)/3), float(f(5*sqrt(3)/3))
5 3 , 1. 443375673 6 Even without further calculations, we can conclude that the function fx 5 3 5 3 has a local maximum y 2 " " 1. 443 4 for x 2 " 6 3 5 3 5 3 " 2. 886 8, local minimum y 3 1. 443 4 for x 3 6 3 2. 886 8 as well as the inflection point y 1 0 for x 1 0.
Chapter 3 ( Introduction to calculus of one variable
117
The next important step is to obtain the asymptotes. We may obtain the vertical asymptotes by calculating discontinuities and checking the limits of function for these points. solve(9*x^2-25, x)
" 53 ,
5 3
limit(f(x), x-5/3, Left)
". limit(f(x), x-5/3, Right)
. limit(f(x), x5/3, Left)
". limit(f(x), x5/3, Right)
. From these calculations we can conclude that we have two vertical asymptotes, x " 5 " 1. 666 7 and x 5 1. 666 7. 3
3
From calculus we know also that the slant asymptotes have a formula y mx b, where m lim fx /x and b lim fx " mx . With MuPAD we xv.
xv.
obtain m : limit(f(x)/x, xinfinity) 1 3
a : limit(f(x)-m*x, xinfinity) 0 and m : limit(f(x)/x, x-infinity) 1 3
a : limit(f(x)-m*x,x-infinity) 0 This shows that for our function there is only one slant asymptote, y x . 3
118
Getting started with MuPAD
Finally, having completed all of the necessary calculations, we can develop a very accurate plot of our function with all the asymptotes and critical points in place. f : x - 3*x^3/(9*x^2-25): // graph of the function F : plot::Function2d(f(x),x-6..6, LineWidth0.50, LineColorRGB::Red, LegendText"Function f(x)" ): // derivative plot G : plot::Function2d(f’(x), x-6..6, LineColorRGB::Blue, LegendText"Derivative f’(x)" ): // slant asymptote A1: plot::Function2d(x/3, x-6..6, LineColorRGB::Gray40, LineStyleDashed, LegendText"Asymptotes" ): // critical points M1 : plot::Point2d([5*sqrt(3)/3,f(5*sqrt(3)/3)], PointSize2, PointStyleXCrosses): M2 : plot::Point2d([-5*sqrt(3)/3,f(-5*sqrt(3)/3)], PointSize2, PointStyleXCrosses): M0 : plot::Point2d([0,f(0)], PointSize2, PointStyleXCrosses ): // plot of the complete scene plot(F,G,A1,M0,M1,M2, // grid parameters XGridVisibleTRUE, YGridVisibleTRUE, XSubgridVisibleTRUE,
Chapter 3 ( Introduction to calculus of one variable
119
YSubgridVisibleTRUE, // annotation parameters LegendVisibleTRUE, Header"Function 3*x^3/(9*x^2-25)", // parameters of background and frame BackgroundColorRGB::Gray80, BorderColorRGB::Black, BorderWidth0.25, // view parameters ScalingConstrained, ViewingBox[-6..6,-3.5..3] )
Function 3*x^3/(9*x^2-25) y
3 2 1
-6
-5
-4
-3
-2
-1
1 -1
2
3
4
5
6
x
-2 -3 Function f(x) Derivative f'(x) Asymptotes
Exercise 3.5 Sketch the graphs of the functions in problems 1 through 5, indicating all critical points, inflection points and asymptotes. 1. fx
x"2 x5
2. fx
x x 2 "x"2
3. fx
x 1x 2
4. fx
x 2 "1 x 2 "3
5. fx
x3 x 2 "1
120
Getting started with MuPAD
3.6 6 Taylor polynomials One of the most important applications of derivatives are the Taylor and Maclaurin series. Their finite versions are well known as Taylor polynomials. We can prove that for a given function fx , if the first n derivatives of the function fx exist, then the polynomials f k a x " a k approximate fx in some neighborhood of k! x a. In other words, fx U P n x in some interval |x " a| /. The closeness with which the Taylor polynomial P n x approximates the function fx is measured by the difference R n x fx " P n x and R n x
P n x
n ! k0
is known as a reminder in Taylor series expansion. We will leave the detailed investigations of this problem to calculus textbooks. Instead, lets us check what this relationship may look like on a graph. In MuPAD, we have the taylor procedure. Using it, we can obtain the Taylor series expansion of a given function fx . Let us check how Taylor polynomials approximate the function sin x. In order to simplify our calculations, we calculate the Taylor expansions for a 0. The procedure taylor requires us to input a formula for the function, the value of a and the degree of the polynomial. Thus, for fx sin x and a 0, the Taylor expansion of degree 1 looks like what we see below. The expression Ox 3 stands for the remainder R 1 x . S taylor(sin(x), x0, 1)
x Ox 3 Next we calculate a few additional Taylor expansions of fx sin x for a 0. In each of the obtained results, the polynomial to the left of Ox k is the Taylor polynomial and Ox k is the remainder. The expressions Ox n are very small in some neighborhood of a. Therefore we can omit them in our calculations. taylor(sin(x), x0, 2)
x Ox 3 taylor(sin(x), x0, 3)
x"
x3 6
Ox 5
Chapter 3 ( Introduction to calculus of one variable
121
taylor(sin(x), x0, 5)
x"
x3 6
x5 120
Ox 7
taylor(sin(x), x0, 7)
x"
x3 6
x5 120
"
x7 5040
Ox 9
It is interesting to show on a graph how consecutive Taylor polynomials approximate the given function. Let us plot a more complicated function y sin x cos x and some of its Taylor polynomials. f : x - sin(x)cos(x): T1 : taylor(f(x), x0, 1): T3 : taylor(f(x), x0, 3): T5 : taylor(f(x), x0, 5): T7 : taylor(f(x), x0, 7): T9 : taylor(f(x), x0, 9): T11 : taylor(f(x), x0, 11): plotfunc2d(f(x),T1,T3,T5, T7, T9, T11, x-2*PI..2*PI, YRange-3..3, LineWidth0.3, XGridVisibleTRUE, YGridVisibleTRUE, XSubgridVisibleTRUE, YSubgridVisibleTRUE, Header"Function sin(x)cos(x) and its Taylor polynomials", HeaderFont["Arial", 12, Bold], LegendVisibleTRUE, BackgroundColorRGB::Gray80, BorderColorRGB::Black, BorderWidth0.2 )
122
Getting started with MuPAD
Function sin(x)+cos(x) and its Taylor polynomials y
3 2 1
-6
-5
-4
-3
-2
-1
-1
1
2
3
4
5
6
x
-2 -3 cos(x) + sin(x) 1 + x + O(x^2) 1 + x - 1/2*x^2 - 1/6*x^3 + O(x^4) 1 + x - 1/2*x^2 - 1/6*x^3 + 1/24*x^4 + 1/120*x^5 + 1 + x - 1/2*x^2 - 1/6*x^3 + 1/24*x^4 + 1/120*x^5 1 + x - 1/2*x^2 - 1/6*x^3 + 1/24*x^4 + 1/120*x^5 1 + x - 1/2*x^2 - 1/6*x^3 + 1/24*x^4 + 1/120*x^5 -
A black-and-white plot does not allow us to distinguish clearly between the graph of the function and those of its Taylor polynomials. We therefore use color. In addition, we have changed the line width of fx to 1mm so it can be clearly distinguished from the other curves. It would be useful for the readers to type the required code into a MuPAD notebook and experiment with it to see how consecutive polynomials approximate the function fx . Exercises 3.6 In problems from 1 through 5, obtain the graph of the given function fx along with its first six Taylor polynomials. 1. fx ln1 x , for a 0 2. fx
1 1"x
, for a 0
3. fx e "x , for a 0 4. fx sin x, for a =/4 5. fx
1 x
, for a 1
Chapter 3 ( Introduction to calculus of one variable
123
3.7 7 Integration with MuPAD Integration in MuPAD requires using the procedure int, introduced in the first chapter. With this procedure, we can produce both indefinite integrals, or so called antiderivatives, as well as definite integrals. In both cases, the syntax of the MuPAD command is very simple. Let us consider a few examples. int(x^23*x5, x) //calculate antiderivative x3 3
3x 2 2
5x
int(x^23*x5,x0..10) //calculate antiderivative 1600 3
int(x*ln(x),x) x 2 lnx " 1 2
2
int(x*ln(x),x0..1)
" 14 S int(sin(x)*cos(x),x) sinx 2 2
Note that MuPAD can easily produce the integrals of some more difficult functions such as y sin2x cos3x or y x sin2x cos3x or even y xe x cos3x . int(sin(2*x)*cos(3*x), x) cosx 2
"
cos5x 4
int(sin(2*x)*cos(3*x), x0..PI)
" 12 int(x*sin(2*x)*cos(x),x) 9 sinx sin3x "3x cos3x "9x cosx 18 cosx 6 54 cosx 4 sinx 2 54 cosx 2 sinx 4 18 sinx 6
Simplify(%)
124
Getting started with MuPAD
sinx 2
sin3x 18
"
x cos3x 6
"
x cosx 2
f : x - x*exp(x)*cos(3*x)
x v x e x cos3 x int(f(x),x) e x 4 cos3x "3 sin3x 5x cos3x 15x sin3x 50
When calculating definite integrals, we can use finite or infinite limits. Here is one of the most interesting examples that we can find in calculus textbooks. F: x -exp(-x^2)
x v e "x
2
2 The function Fx e "x is known as the Gauss function. Here is its graph:
plotfunc2d(F(x), x-2..2, YRange0..1) y
1
0.8
0.6
0.4
0.2
-2
-1.8
-1.6
-1.4
-1.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
x
Let us calculate the integral of the Gauss function for "., . . int(F(x), x-infinity..infinity)
= Here is another example where we obtain a definite integral with infinite limits. G : x - 1/(x^21)
xv
1 x 2 1
Chapter 3 ( Introduction to calculus of one variable
y
125
1 0.8 0.6 0.4 0.2
-2
-1.8
-1.6
-1.4
-1.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
x
int(G(x), x-infinity..infinity)
= In many examples, the definite integral is interpreted as the relative area between the graph of the function and x-axis. Relative in the sense that result is a positive number for fx u 0 and a negative for fx t 0. It is sometimes useful to produce a graph of the function where we mark the area between the curve and the x-axis. Such graphs can be obtained using the plot object plot::Hatch(F,a..b). Occasionally, we need to produce a graph where the area between two curves is shaded. For this purpose, we use the statement Hatch(F1, F2, a..b). In each case, F, F1 and F2 are graphical objects declared as Function2d or Curve2d. Note that we give the range of the variable x as a..b, which is different from the usual statement xa..b. The Hatch class accepts a number of parameters. However, we can add most of them in the Virtual Camera. Finally, let us note that Hatch represents only the shaded area and it does not contain the curves F1 and F2. Therefore, in order to get a complete plot, we have to plot F, or F1, F2 and the shade between them. Let us declare the function gx x 3 " x 2 " 6x. g : x - x^3-x^2-6*x
x v x3 " x2 " 6 x Suppose that we want to calculate the area between gx and x-axis. We can easily find out that
3 ; "2 x 3 " x 2 " 6x dx "
125 . This means that the 12
area between the graph of gx and the x-axis is negative. This slightly confusing fact can easily be illustrated using plot::Hatch.
126
Getting started with MuPAD
G : plot::Function2d(g(x), x-2.5..3.5): H : plot::Hatch(G, -2..3, FillPatternSolid, FillColor[0.5, 0.67, 0.87] ): plot(H, G, AxesInFrontTRUE) y 8 6 4 2
-2.5
-2.0
-1.5
-1.0
-0.5
0.5 -2
1.0
1.5
2.0
2.5
3.0
3.5
x
-4 -6 -8
This tells us what is going on. The function gx has two parts. The left part (for "2 x 0) has a positive integral, while the right part of the function (for 0 x 3) has negative values and its integral is also negative. Therefore, in order to calculate the total area between the function and the x-axis, we have to split our integral into two separate parts and use the absolute value of the second integral: area : int(g(x),x-2..0)abs(int(g(x),x0..3))
253 12 Technical comment When plotting Hatch in the final plot statement, we used a specific order of objects to be plotted. First we placed H and then G. It is important to note that if we plot Hatch as the last object, its area will cover at least partially the curve and coordinate axes. Therefore, to avoid this unwanted effect, we plot Hatch first and then the other objects. Finally, we have to move the coordinate axes to the front. For this purpose, we use the parameter AxesInFrontTRUE.
Chapter 3 ( Introduction to calculus of one variable
127
Exercise 3.7 In problems 1 through 5, the graphs of fx , gx and the x-axis divide the xy-plane into several regions. Some of them are bounded. Plot a graph for each of these functions, use plot::Hatch to mark the bounded regions. Finally, find the total area of the bounded regions in each problem. 1. fx 2x 3 , gx x 2. fx x 3 " 9x, gx 10x 3. fx x sin x for x 0. . 4= 4. fx o 8 " x , gx x/2 5. fx |x 3 " x 2 " 6x|, gx 2
3.8 8 Numerical integration There are a few functions for which calculating integrals using antiderivatives cannot be done. In such cases, we use numerical integration. Let us consider the function sinx x . Its antiderivative cannot be expressed by means of elementary functions. Therefore, when calculating its integral, we do not get a formula like those that we got in the previous section. int(sin(x)/x, x)
Six int(sin(x)/x, x0..PI)
Si= However, we still can obtain an approximate value of the definite integral using the numeric::int procedure: numeric::int(sin(x)/x, x0..PI) 1.851937052 2
Another such example is the mentioned Gauss function e "x . In the previous section, we calculated its integral for ". x .. However, attempts at calculating its antiderivative or definite integral over a finite
128
Getting started with MuPAD
interval fail. F: x -exp(-x^2): int(F(x), x)
= erfx 2 int(F(x), x0..PI)
erf= = 2 In this case, numerical integration produces the desired result. numeric::int(F(x), x0..PI) 0.8862190592 Technical comment The functions erfx and Six obtained in our examples belong to a group of functions known as special functions. Such functions occur quite frequently in integration or when solving integral equations. There are a number of methods that can be used to produce the approximate values of integrals. Some of them, like the Riemann, Simpson or trapezoid methods, can be found in any calculus textbook. It is interesting to visualize how these methods approximate the value of an integral. 2
Let us return to the function fx e "x . We show how MuPAD can help us to visualize the process of integrating fx on ¡"1. . 1¢. We will use the procedure plotRiemann from the student library. A : student::plotRiemann(exp(-x^2), x -1..1, 5): plot(A)
Chapter 3 ( Introduction to calculus of one variable
Lower: 1.24 Upper: 1.73 Integral: 1.49
129
y 1
0.8
0.6
0.4
0.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
Note that the number 5 used in the plotRiemann statement defines the number of rectangles used to approximate the integral. Here are two more plots, using 10 and 50 rectangles respectively. A : student::plotRiemann(exp(-x^2),x-1..1,10): plot(A) Lower: 1.36 Upper: 1.62 Integral: 1.49
y 1
0.8
0.6
0.4
0.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
A : student::plotRiemann(exp(-x^2),x -1..1,50): plot(A)
130
Getting started with MuPAD
Lower: 1.47 Upper: 1.52 Integral: 1.49
y 1
0.8
0.6
0.4
0.2
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
The plotRieman procedure produces not only a picture but also numbers showing the total area of the rectangles under the curve, the total area of the rectangles covering the curve as well as the final integral. Therefore, we have, Number of rectangles in the Riemann method 5
10
50
Lower approximation
1. 24 1. 36 1. 47
Upper approximation
1. 73 1. 62 1. 52
Final integral
1. 49 1. 49 1. 49
The student library contains two other procedures for visualizing the results of numerical integration. These are plotTrapezoid and plotSimpson. Their syntax is exactly the same as for plotRieman.
Chapter 3 ( Introduction to calculus of one variable
131
B : student::plotTrapezoid(exp(-x^2),x-1..1, 10): plot(B) Trapezoidal: 1.489 real: 1.494
y
1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
B : student::plotSimpson(exp(-x^2), x -1..1, 10): plot(B) y
simpson: 1.494 real: 1.494
1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
132
Getting started with MuPAD
Exercise 3.8 In problems 1 through 5, visualize the Riemann approximation R n of the given integral and compare the obtained result with the exact value of the integral. Use the indicated number n of rectangles. 2
1.
; 0 x 2 dx, for n 5
2.
; "1
3.
;0
1
1 x2
dx, for n 3, 5, 7
1 tan x x
4. ln 2 5. =
dx, for n 5, 10 2
; 1 1x dx, for n 3, 7, 11 1
;0
4 1x 2
dx, for n 3, 7, 11
3.9 9 Solving differential equations In MuPAD we can solve many different types of differential equations. However, the topic is beyond of the scope of this book. Therefore, we will restrict our considerations to one simple example. You can find more information about solving differential equations in MuPAD’s help files (type in ?ode or help(ode)). In order for MuPAD to recognize a given equation as a differential equation and solve it properly, we apply the ode procedure. For example, the statement diff_eq : ode( y’(x) - 2*y(x)*cos(x) cos(x)sin(2*x), y(x) ): declares the variable diff_eq as a differential equation y U " 2y cos x sin 2x, where y yx . We can solve this equation using the well known procedure solve. A : solve(diff_eq)
£C2 e 2sinx " sinx " 1¤ We have obtained an equation for a family of functions determined by the parameter C2. Depending on the values of C2, we obtain different functions.
Chapter 3 ( Introduction to calculus of one variable
133
Technical comment In many situations similar to the one above, MuPAD creates new parameters such as C2, C34, C76, etc. Try, for example, to execute the statement solve(diff_eq) several times. Each time, a new parameter with a different name is created. Therefore, there is a great likelihood that the parameters created by MuPAD in my examples differ from those produced in your experiments. Let us suppose that we intend to study the solutions with the integer parameters C2 "10, . . 10. We can extract these solutions using the sequence operator $ and substituting appropriate integer values for C2. Eq : op(A) // remove the curly brace
C2 e 2sinx " sinx " 1 Functions : Eq $ C2-10..10: // create functions We can then plot all the functions on the same coordinate system: plotfunc2d(Functions, x-1.5..4.5, LegendVisibleFALSE ) y 60
40
20
-1.5
-1.0
-0.5
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
x
-20
-40
-60
In a very similar way we can solve and visualize other differential equations. We leave this topic for further exploration by the readers.
134
Getting started with MuPAD
Before we finish this section, however, it is worth mentioning that MuPAD has a special library ode with tools for experimenting with differential equations, as well as the library detools, with tools for more complex problems associated with the solution of differential equations. Exercise 3.9 In problems 1 trough 7, solve the given differential equations and visualize the indicated functions for the families of solutions obtained. For each problem, find a solution satisfying the given condition. 1.
dy dx
2x 1, y0 3
2.
dy dx
3.
dy dx
x " 2 3 , y2 1
4.
dy dx
5.
dy dx
1 x2
6.
dy dx
x 9 , y"4 0
7.
dy dx
3x 3
3 , y4 0
1 x2
, y1 5 , y2 "1
2 x3
, y1 1.
Multivariable calculus Extending calculus in one variable to calculus in several variables, referred to in this book as multivariable calculus, involves additional steps and requires some new concepts. However, for most of topics we will be able to use the procedures discussed in chapter 3, changing certain aspects of our approach and adapting the already presented methods. In order to simplify our investigations we limit ourselves, where possible, to functions of two variables. This will be enough for us to understand most of the basic concepts. Occasionally, we may need to go beyond two variables.
4.1 1 Functions of several variables Let us start from scratch by reviewing how to declare functions, this time, however, functions of many variables. The major difference in the declaration is the round-bracket grouping of the variables of the function. Here are a few simple examples. F : (x,y) - sin(x)*cos(y)
x, y ¯ sinx cosy Distance : (x,y,z) - sqrt(x^2 y^2 z^2)
136
Getting started with MuPAD
x, y, z ¯
x2 y2 z2
Temperature : (x,y,z,t) - (4*PI*k*t)^(-3/2)*exp(-(x^2y^2z^2)/(4*k*t)) x 2 y 2 z 2
e " 4kt x, y, z, t v 3 4 = k t 2 In exactly the same way we can declare functions F : h n v h m or even F : [ n v [ m , where h and [ are real and complex numbers, respectively. For example, a transformation from Cartesian coordinates to spherical coordinates can be declared as follows: S2C : (r,t,u)- (r*sin(t)*cos(u),r*sin(t)*sin(u), r*cos(t))
r, t, u v r sin t cos u, r sin t sin u, r cos t We will return to this function later when talking about the integrals of functions of several variables. As in the case of functions of one variable, we can deal with piecewise functions of several variables. However, in such cases, we usually have more conditions. Let us declare a function of two variables fx, y such that fx, y n where n 1 for x 0 and y 0; n 2 for x 0 and y 0; n 3 for x 0 and y 0; and n 4 for x 0 and y 0. Here is the declaration of such a function: steps [x [x [x [x ):
: (x,y) - 0 and y 0 and y 0 and y 0 and y
piecewise( 0, 1], 0, 2], 0, 3], 0, 4]
We can use our declarations to calculate some values. F(PI/3,PI/3)
3 4 Distance(1,1,1)
3
Chapter 4 ( Multivariable claculus
137
Temperature(1,1,1,1) " 3
e 4k 3
4=k 2
steps(1,1) 1 steps(-2,3) 2 steps(0,0) undefined In this last case, MuPAD did not produce a value. However, this is our fault. We did not define our function for some arguments. For piecewise functions of several variables we must apply the same rules as those learned while talking about piecewise functions of one variable. When working with functions of several variables, we often need to determine the domain of the function, that is, a set of arguments for which we can calculate the values of the function. For example, the x 2 " 2y 2 is the set
domain of the function of two variables fx, y Df
x, y 3 x 2 " 2y 2 u 0 . This set can be easily plotted with the use of
the plot::Inequality class. Df : plot::Inequality(x^2-2*y^20, x-5..5, y-5..5, Mesh[100,100], FillColorFalseRGB::Gray80 ): plot(Df) y
5 4 3 2 1
-5
-4
-3
-2
-1
1 -1 -2 -3 -4 -5
2
3
4
5
x
138
Getting started with MuPAD
The dark area represents the domain of the function fx, y . This is the area where the inequality is true. In the case of functions of three variables, plotting their domain requires stronger tools, for example, parametric and implicit plots in 3D. Exercise 4.1 In problems 1 through 5, declare the given function and state the domain of the function. Where possible, use plot::Inequality to plot the domain or part of it. 1. fx, y
4 " x2 " y2
2. fx, y lnx 2 " y 2 " 1 3. fx, y 4. fx, y 5. fx, y
1 x"y 1"x 2 1 1"y 2 xy x 2 y
4.2 2 Visualizing functions of several variables In the second chapter, we learned about the plotfunc3d procedure and the plot::Function3d class. We can use them to visualize functions of two variables, as well as functions of three variables. Let us look at what we can produce: plotfunc3d(F(x,y), x-PI..PI, y-PI..PI)
Chapter 4 ( Multivariable claculus
139
plotfunc3d(steps(x,y), x-1..1, y-1..1)
Note that obtaining the plot of the function stepsx, y took a bit longer than Fx, y . This is because the calculation of the values of this function requires checking a number of conditions for each pair x, y . For example, to calculate the value steps1, "1 MuPAD had to check eight consecutive conditions. Plotting graphs of functions of three or more variables is not possible. However, in some sense, we can still produce graphs representing these functions. For example, we can plot intersections of the hypersurface with some 3D subspaces of h 4 . There is some analogy to plotting the cross-section of a graph of one variable function with a line perpendicular to one of the axes of the coordinate system. Suppose that we are investigating the function Kx, y, t sin x sin 2y sin 3t. We cannot produce a graph of this function in h 3 . However, we can show the cross-sections of this function with the hyperplanes t 0, t 0. 5, t 1, and so on. Let us produce these plots. K : (x,y,t) - sin(x)*sin(2*y)*sin(3*t): plotfunc3d(K(x,y,0), x-PI..PI, y-PI..PI)
140
Getting started with MuPAD
In order to show the right proportions of the graph in the next plots, we use the parameter ScalingConstrained. This ensures that the units on all axes have the same length. plotfunc3d(K(x,y,0.5), x-PI..PI, y-PI..PI, ScalingConstrained )
Chapter 4 ( Multivariable claculus
141
plotfunc3d(K(x,y,1), x-PI..PI, y-PI..PI, ScalingConstrained )
Another good way of visualizing functions of three variables is animation. We can treat one of the variables as the time and show how z fx, y, t changes as time goes on. A good example of such visualization can be obtained by executing the following code, f : (x,y,t) - (x^2y^2)*t^2: S4D : plot::Function3d( f(x,y,t),x-2..2,y-2..2, t0..3 ): plot(S4D) Graphs obtained with the help of plotfunc3d or plot::Function3d using the natural MuPAD colors, red and blue, show up well the shape of the surface and its elevation. However, they do not show several other features. For example, sometimes it would be useful to see the surface with its horizontal cross-sections, the so-called contour curves, or to examine how steep the surface is in some places. These features of surfaces can be visualized using other tools. Let us define a function of two variables. h : (x,y) - 9*(x^2-y^2)*exp(-x^2-y^2)
x, y v 9 x 2 " y 2 e "x
2 "y 2
First we obtain the standard plot of this surface with natural MuPAD colors. a : 2.5: b:2.5: H : plot::Function3d(h(x,y), x-a..a, y-b..b): plot(H)
142
Getting started with MuPAD
Next we can produce its density plot for the same range of the variables x and y. DP : plot::Density(h(x,y), x-a..a, y-b..b, Mesh[50,50], FillColorRGB::White, FillColor2RGB::Indigo): plot(DP)
In this graph, we can easily recognize the top and bottom parts of the surface and see how quickly the color changes from white to dark blue. Another way of visualizing our surface is to plot only its contour curves. CP : plot::Function3d(h(x,y), x-a..a, y-b..b, ZContours[n/5 $ n-20..20],// show contours XLinesVisibleFALSE, //hide mesh for x
Chapter 4 ( Multivariable claculus YLinesVisibleFALSE, FilledFALSE
143
//hide mesh for y //hide the surface
): plot(CP)
Finally, another way of exploring the shapes of surfaces is animation. We can animate the surface in many ways. The simplest one is by animating the range of one or both variables. In this way we can examine the vertical cross-sections. This can be done as follows, for example: H : plot::Function3d(h(x,y), x-2.5..c, y-2.5..c, c-2.5..2.5 ): plot(H) At this point, we leave the various ways of visualizing functions and move on to another topic. Before doing so, however, we need to practice with a few more examples. Exercise 4.2 In problems 1 through 5, produce a standard graph of the given function and then obtain its density plot, as well as its contour curves. 1. fx, y
1cos xy
2. fx, y
1sin xy xy
x 2 y 2
3. fx, y cosx 2 y 2 4. fx, y x 2 e "x
2 "y 2
5. fx, y xy sinx/y
144
Getting started with MuPAD
4.3 3 Limits of functions of several variables Calculating the limits of functions of several variables can be much more complicated than calculating the limits of functions of one variable. In order to simplify the topic, we will therefore restrict our investigations to limits of functions of two variables only. Let us suppose that we have a function of two variables fx, y and wish to calculate the limit lim x,y vx ,y fx, y . What does this really mean? 0 0
Recall that in the case of functions of one variable, a limit for x ¯ x 0 sometimes does not exist. This forces us to investigate the left and right limits. However, we were still able to calculate the results using one command, limit, with some additional parameters. When talking about a limit of fx, y for x, y ¯ x 0 , y 0 we may have to consider more than two choices. For example, we may have to calculate the limit when x ¯ x 0 and then for y ¯ y 0 or vice versa. We can suppose that x, y goes to x 0 , y 0 along a straight line or along any other curve passing through the point x 0 , y 0 , for example along a spiral with the center in x 0 , y 0 . If in each of the mentioned cases the result is the same final number A, then we say that lim x,y vx ,y fx, y A. 0 0
For many functions of two variables calculating the limit is rather simple—we calculate, for example, the limit for x v x 0 and then for y v y0. Let us check a few examples. f : (x,y) - sin(x*y)
x, y ¯ sinx y limit(f(x,y), xPI/2)
sin
=y 2
limit(%, yPI/2)
sin
=2 4
float(%)
0. 6242658526
Chapter 4 ( Multivariable claculus
145
We can combine these statements into a single command, as follows: float(limit(limit(f(x,y), xPI/2), yPI/2))
0. 6242658526 Here is another example: we calculate
1"xy lim . x,y ¯1,1 1xy
g : (x,y) - (1-x*y)/(1x*y)
x, y ¯
1"xy 1xy
limit(limit(g(x,y), x1), y1) 0 limit(limit(g(x,y), y1), x1) 0 Let us consider one more example. We investigate the function x 2 "y 2 and its limit for x, y v 0, 0 . We can easily see that for x 2 y 2 x 0 and y 0 the function has the form 0 . This suggests that we must 0
hx, y
be careful in our investigations. Let us declare our function first and then calculate some limits. h : (x,y) - (x^2-y^2)/(x^2y^2)
x, y ¯
x2 " y2 x2 y2
limit(limit(h(x,y), x0),y0) -1 limit(limit(h(x,y), y0), x0) 1 x2 " y2 x2 y2 as x, y v 0, 0 does not exist. However, from this example we may learn a little more. Let us try to find the limit of hx, y along any straight line passing through the point 0, 0 . This requires us to substitute y mx into our equation and calculate the limit for x v 0. We obtained two different results. This suggests that the limit of
146
Getting started with MuPAD
Here are the calculations: H : subs(h(x,y), ym*x) 2 2
2
" m 2 x 2 "x 2 m x x
H : simplify(H) 2
" m 2 "1 m 1
The final expression H does not contain x. Therefore lim xv0 H H. Now we can try to find the value of H for different values of m. subs(H, m1) 0 subs(H, m2)
" 35 subs(final, m3)
" 45 subs(H, m4)
" 15 17 In each case, we get a different result. This means that for P 0, 0 the limit from each direction is different. How is this possible? In order to find it out, we plot hx, y and show on the plot what it means that x, y v 0, 0 along a line y mx. First let us note that by substituting y mx into z
x 2 "y 2 we obtain a family of lines in 3D in the parametric x 2 y 2
form: Cm : x v
2
x, mx, " m 2 "1 m 1
and each of these lines lies on the surface z fx, y and passes through 2
the point 0, 0, " m 2 "1 . m 1
Therefore, we can try to plot the function hx, y , with some of the lines C m . Let us make the necessary declarations.
Chapter 4 ( Multivariable claculus
147
h : (x,y)-(x^2-y^2)/(x^2y^2): C : (x,m) - [x, m*x, -(m^2-1)/(m^21)]: C1 : plot::Curve3d( subs(C(x,m),m1), x-1..1, UMesh2, LineWidth0.5 ): C2 : plot::Curve3d( subs(C(x,m),m2), x-1..1, UMesh2, LineWidth1 ): C3 : plot::Curve3d( subs(C(x,m),m-1/2), x-1..1, UMesh2, LineWidth1.5 ): H : plot::Function3d(h(x,y), x-1..1, y-1..1): plot(H, C1, C2, C3)
Technical comment When talking about functions of one variable we noticed that plots produced in MuPAD may not be accurate if the function has high jumps or many jumps in a given interval. The same observations apply when plotting graphs in 3D. The graph we obtained earlier has a gap in lower half as we see it in the picture above. In order to get a more accurate view and close the gap, if possible, we make a denser mesh of the surface. For example
148
Getting started with MuPAD
Submesh[2,2] or AdaptiveMesh2 will improve the accuracy of the graph. Exercise 4.3 In problems 1 through 5, find the limit or show that no limit exist. Use accurate graphs to verify your result. 1. 2.
lim
1 " xy 1 xy
x,y v0,0
lim
sin xy xy
lim
1 2y2 x e
x,y v1,1
"
3. 4. 5.
x,y v0,0
lim
x,y v0,0
lim
x,y v0,0
x3 y3 x2 y2 xy x2 y2
4.4 4 Partial differentiation Calculating the derivatives of functions of two or more variables is very similar to the differentiation of functions of one variable. The only difference is that we may have a few, so called partial derivatives of the same order, for example
f f f f , , , etc. where, for example, means x y z x
derivative of fx, y, z in respect to the variable x. Let us examine a few examples. h : (x,y) - x*y/(x^2y^2)
x, y ¯
xy x y2 2
diff(h(x,y), x) // first derivative in x
y 2 x2 y " 2 x2 y2 x 2 y 2
Chapter 4 ( Multivariable claculus
149
diff(h(x,y), y) // first derivative in y
2 x y2 x " x2 y2 x 2 y 2 2 diff(h(x,y), x,y) // mixed derivative for x,y 2 2 y2 8 x2 y2 1 " " 2x 2 2 2 x y x 2 y 2 x 2 y 2 x 2 y 2 3 2
diff(h(x,y), x,x) // second derivative in x
8 x3 y 6xy " 3 2 x 2 y 2 x 2 y 2 We can use the derivatives of the function of two variables to calculate and display tangent planes to a given surface, vectors normal to a surface, and other elements. In each case, we need some basic knowledge of analytic geometry. For example, in order to obtain a tangent plane to a given surface we need to know the equation of the tangent plane: z
f f a, b x " a a, b y " b fa, b x y
This will allow us to produce a graph for a given function of two variables and some of its tangent planes. I will leave these easy step-by-step calculations to my readers as a simple exercise. However, we will use the above formula to show how certain calculus problems can be turned into black box routines where users only need to enter the basic data to get the final result. Let us observe that the equation of the tangent plane can be considered as a function of two variables a and b. For the two given values of a and b, we obtain a new plane tangent to fx, y . To begin, let us declare the function fx, y and the tangent plane function. f : (x,y) - 5-2*x^2-y^2: TangentPlane : (a,b)-( subs(diff(f(x,y),x),xa, yb)*(x-a) subs(diff(f(x,y),y),xa, yb)*(y-b) f(a,b) ):
150
Getting started with MuPAD
We can use the new TangentPlane function to produce and plot a number of planes tangent to fx, y . plotfunc3d( f(x,y), TangentPlane(1,1), TangentPlane(-2,-2) )
The obtained picture was modified in the Virtual Camera. The colors of the planes were changed and some transparency was added to highlight the points where the planes are tangent. It would be instructive for the reader to change the formula of fx, y to x 2 y 2 , for example, and execute the corresponding code to see what MuPAD produces this time. Exercise 4.4 In problems 1 through 5, find the equation of the plane tangent to the surface z fx, y at the given point A. 1. z x 2 xy y 2 , A 1, 1, 3 2. z x 3 " y 3 , A 1, 2, "7 3. z xy, A "1, "1, 1 4. z e "x
2 "y 2
, A 1, 1, e "2
5. z x 2 " 5y 2 , A 2, 1, "1
Chapter 4 ( Multivariable claculus
151
4.5 5 Vector fields In mathematics as well as in engineering, we can find many applications of vector fields. In this section we will only touch on the topic by discussing some basic elements. A vector field over the region S in 2D space is a vector-valued function Vx, y iFx, y jGx, y where i, j are unit vectors and Fx, y , Gx, y are functions of two variables. We also have vector fields in 3D. In this case, Vx, y, z is a vector-valued function of three variables: Vx, y, z iFx, y, z jGx, y, z kHx, y, z For a given function fx, y , we can create a vector field f i
f f j , x y
known in textbooks as a gradient vector field. We can prove that for any given x, y , the expression fx, y represents a vector pointing in the direction where the function increases most rapidly, and its length represents the rate of increase of f. The same is of course true for gradient vector fields in 3D. Therefore, the graphs of gradient vector fields can be useful tools for visualizing and analyzing functions of 2 and 3 variables. Let us start with the declaration of a function of two variables, and then plot its vector field. z : (x,y)-sin(x)*cos(y)
x, y v sinx cosy F : diff(z(x,y),x): G : diff(z(x,y),y): V : plot::VectorField2d([F,G], x-2..2, y-2..2, Mesh[15,15] ): plot(V)
152
Getting started with MuPAD
y
2
1
-2.0
-1.5
-1.0
-0.5
0.5
1.0
1.5
2.0
x
-1
-2
It is interesting to generate a regular plot of z sin x cos y and then compare the graph of the function and its vector field to see the dependencies between them.
We can see that in the gradient vector field of z, the arrows point to where the function takes the largest values (the light area). Gradient vector fields of functions of three variables play a similar role and are even more useful since we cannot plot functions of 3 variables. Here is an example of a gradient vector field for the function Ux, y, z 1 " x " 1 2 y " 1 2 z " 1 2
Chapter 4 ( Multivariable claculus
153
We note that the largest value of the function is obtained for x 1, y 1, and z 1. This can be seen on the gradient vector field of the function. On the graph, the point 1, 1, 1 is plotted as a large red square. reset(): u : (x,y,z)-1-((x-1)^2(y-1)^2(z-1)^2): F : diff(u(x,y,z),x): G : diff(u(x,y,z),y): H : diff(u(x,y,z),z): V : plot::VectorField3d([F,G,H], x-2..2, y-2..2, z-2..2, Mesh[10,10,10], PointSize1 ): P : plot::Point3d([1,1,1], PointColorRGB::Red, PointSize3, PointStyleFilledSquares ): plot(V,P)
Technical comment The 3D vector field class in MuPAD uses a dot instead of an arrow. In other words, the dot replaces the arrow tip. This way the picture is much clear. Exercise 4.5 In problems 1 through 5, use MuPAD to calculate and plot the gradient vector field of the given function. Show on the graph the points where the function takes minimal and maximal values.
154
Getting started with MuPAD
1. fx, y sinxy 2. fx, y 3x 2 xy 2y 2 3. fx, y sin 3x cos 5x 4. fx, y, z xy 2 z 3 5. fx, y, z xe "x
2 y 2 z 2
4.6 6 Multiple integrals with MuPAD Integration of functions with several variables in MuPAD requires the same procedure int that we used in the previous chapter. In order to obtain the multiple integral, ;C; fx 1 , x 2 , . . , x n dx 1 dx 2 . . dx n we have to integrate f with respect to the variable x 1 , then integrate the obtained result with respect to x 2 and so on. Let us see how we can calculate the integrals ; ;3x 7y dxdy, ; ;x 2 y 2 dxdy, ; ; ; xyzdxdydz. int(int(3*x7*y, x),y)
3 x 7 y 3 126 int(int(x^2y^2, x),y)
x3 y x y3 3 3 int(int(int(x*y*z, x), y), z)
x2 y2 z2 8 The same multiple integral can be calculated step-by-step as follows: int(x*y*z, x)
x2 y z 2 int(%,y)
x2 y2 z 4
Chapter 4 ( Multivariable claculus
155
int(%,z)
x2 y2 z2 8 In exactly the same way we calculate multiple, definite integrals. Let us see, for example, how we can find the value of ;
1 1 2 ; x y 2 dxdy. 0 0
int(int(x^2y^2, x0..1), y0..1)
2 3 In practice, we often need to calculate multiple integrals over an area that is not a rectangle or a rectangular block with sides parallel to the planes of the coordinate system. For instance, suppose that we want to obtain the integral ;; 3x 2 5y 2 dxdy, where D is the area bounded by the curves D
y sin x and y " sin x for 0 t x t = (check fig. 4.1). y
1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8
1
1.2 1.4 1.6 1.8
2
2.2 2.4 2.6 2.8
-0.2
3
x
-0.4 -0.6 -0.8 -1
Fig. 4.1 Area bounded by y sin x and y " sin x Calculating such integrals can be done step by step. We begin by declaring the function fx, y 3x 2 5y 2 . f : (x,y) - (3*x^2 5*y^2)
x, y ¯ 3 x 2 5 y 2
156
Getting started with MuPAD
Then we calculate the integral with respect to y, for " sin x t y t sin x. int(f(x,y), y-sin(x)..sin(x))
6 x 2 sinx
10 sinx 3 3
Finally, we calculate the integral with respect to x, for x 0. . =. int(%, x0..PI)
6 =2 "
176 9
The same integral can be calculated using a single statement. int(int(f(x,y), y-sin(x)..sin(x)),x0..PI)
6 =2 "
176 9
In many multiple integrals, changing variables may not be as easy as it was in our last example. Very often, we have to change the variables in such a way that a new integral will be calculated over a region with simpler boundaries. Let us examine one more example. We are going to calculate the integral
;;; V
x x 2 y 2 z 2
, where V is a region
bounded by the surface x 2 y 2 z 2 x. In order to calculate this integral, we have to change the variables so that the region V turns into a shape with simple boundaries, possibly into a rectangular block. The shape of both formulae suggests that transforming our integral into an integral in spherical coordinates may produce a satisfactory result. Let us remind ourselves of the formula for converting Cartesian coordinates to spherical coordinates: x, y, z r sin t cos u, r sin t sin u, r cos t or, in a more convenient form, x r sin t cos u y r sin t sin u z r cos t where r, t, u are real variables representing position of a point P in 3D. Here r is the distance from P to the origin O; u is the angle between the positive direction of the x-axis and the line segment OP U , where PU is the
Chapter 4 ( Multivariable claculus
157
projection of P on the xy-plane, and finally t is the angle between the positive part of the z-axis and the line segment OP. Therefore, after substituting the spherical representation of x, y, z into the equation of the region we get: V : (x^2y^2z^2x)
x2 y2 z2 x x : r*sin(t)*cos(u): y : r*sin(t)*sin(u): z : r*cos(t): simplify(V) assuming r0
r cos u sin t This simple equation can be plotted using the plot::Spherical class. plot::Spherical([cos(u)*sin(t), u, t], u0..2*PI, t0..PI ): plot(%)
Note that in this graph, the coordinate system, colors and some other parameters were changed in the Virtual Camera. Now, we need to think how we can convert the integral to an integral in spherical coordinates for which we can calculate its value. In calculus textbooks we can find a formula that will help us:
158
Getting started with MuPAD
;;; Fx, y, z dxdydz ;;; Gr, t, u V
S
x, y, z drdtdu r, t, u
where, S is the new region, Gr, t, u is the function obtained from Fx, y, z after transformation, and finally the so-called Jacobian has the formula
x, y, z r, t, u
x r y r z r
x t y t z t
x u y u z u
It looks as though we have done half of the work. After transforming it into spherical coordinates, the region V changes into the block ¡0, cos u sin t¢ ¡0, 2=¢ ¡0, =¢. Now we have to transform the function Fx, y, z into spherical coordinates, calculate the Jacobian and then obtain the integral. Let us start by transforming Fx, y, z . reset(): F : x/sqrt(x^2y^2z^2)
x x y2 z2 2
x : r*sin(t)*cos(u): y : r*sin(t)*sin(u): z : r*cos(t): MuPAD will automatically replace x, y, z in the expression Fx, y, z and produce an expression Gr, t, u . G : x/sqrt(x^2y^2z^2)
r cosu sint r 2 cost 2 r 2 cosu 2 sint 2 r 2 sint 2 sinu 2 G : simplify(G) assuming r0
cosu sint Calculating the Jacobian requires a few new procedures that we have not yet learned. We need to use the matrix procedure to produce a matrix and linalg::det to calculate the determinant of a matrix.
Chapter 4 ( Multivariable claculus
159
Jacobian : matrix(3,3, [[diff(x,r), diff(x,t),diff(x,u)], [diff(y,r), diff(y,t),diff(y,u)], [diff(z,r), diff(z,t),diff(z,u)]] )
sin t cos u r cos t cos u "r sin t sin u sin t sin u r cos t sin u cos t
r sin t cos u
"r sin t
0
Jacobian : simplify(linalg::det(Jacobian))
r 2 sint int( int( int(G*Jacobian, r0..cos(u)*sin(t)), u0..2*PI), t0..PI)
4= 15 Exercise 4.6 1. Let V be the region bounded by the lines x y 1, x y 2, x " y 1 and x " y 2. Use the substitution u x y, v x " y to calculate the integral ;; dxdy. V
2. Let V be the region between two circles x 2 y 2 1 and x 2 y 2 2. Use polar coordinates to calculate the integral ;; x 2 xy y 2 dxdy. V
x2,
3. Let V be the region bounded by the lines y y 3x 2 , x y 2 , x 3y 2 . Find the most convenient substitution to calculate the area of V. 4. Calculate the volume of the region bounded by the surface given by the equation x 2/3 y 2/3 z 2/3 1. 5. Calculate the integral ;;
dxdy V
x 2 y 2
2
for the region V bounded by the
following curves xy 1, xy 3, x/y 1, x/y 3 and x 0.
160
Getting started with MuPAD
4.7 7 Visualizing and calculating volumes One of the applications of multiple integrals is calculating areas and volumes determined by curves and surfaces. Let us solve one of the typical exercises that we can find in calculus textbooks. Suppose that we have to calculate the volume of a bowl shown in the figure 4.2. This is a solid obtained from a paraboloid z x 2 y 2 , cut by the planes z 4 and z 9. The height of the bowl is 5 units, z 4. . 9.
Fig. 4.2 The paraboloid z x 2 y 2 cut by the plane z 4 It is important to notice that the volume can be calculated and visualized in many different ways. Some of them are quite complicated and some others are fairly simple. In our example, we can try to solve the problem using detailed numbers or by producing a general solution. We can try to use different coordinate systems or even some other simpler means. To begin, let us note that we can produce the volume of the bowl by calculating the volume of the larger paraboloid and subtracting from it the volume of the small paraboloid at the bottom. This leads us to a more general question—what is the volume of the paraboloid z ax 2 y 2 for z 0. . h?
Chapter 4 ( Multivariable claculus
161
Observe that this volume can be expressed as =R 2 h " ;; ax 2 y 2 dxdy, S
where =R 2 h is the volume of a cylinder wrapping the paraboloid and R is the radius of the top circle of the paraboloid. To visualize this situation, we need to calculate R, and plot the surface of the cylinder and the region S on the same graph. The region S will be a circle with the radius R on the xy-plane, whereas the cylinder can be plotted using the plot::Sweep class. Let us start the calculations by obtaining R. It is easy to see that the equation of the top circle can be expressed as the intersection of the two surfaces z ax 2 y 2 and z h. We can transform it into parametric form by substituting x R cos t, y R sin t and z h. In this way we get: SURF : z a*(x^2y^2): TopCircle : subs(SURF, zh, xR*cos(t), yR*sin(t))
h a R 2 cost 2 R 2 sint 2 TopCircle : simplify(TopCircle)
h R2 a Hence, R
h . Note also that the equation of the surface z ax 2 y 2 , a
after changing the coordinates to x r cos t, y r sin t and z z, changes to z ar 2 where r 0. . R and t 0. . 2=. The coordinates that we used here are known as cylindrical coordinates. After these introductory explanations, we can develop the graph. For this purpose, we use a : 1: h : 9: R : sqrt(h/a): TopCurveEq : t - [R*cos(t),R*sin(t),h]
t v ¡R cost , R sint , h¢ Cylinder : plot::Sweep(TopCurveEq(t), t0..2*PI, FillColor[0,1,0,0.2], FillColorTypeFlat ):
162
Getting started with MuPAD
Surface : plot::Cylindrical( [sqrt(z/a),t,z], t0..2*PI, z0..h ): BaseCircle : plot::Circle3d(R, [0,0,0], [0,0,1], FillColorRGB::Red, FilledTRUE ): plot(Cylinder, Surface, BaseCircle, ScalingUnconstrained )
Now, we can calculate the volume of the paraboloid. To calculate the integral we use cylindrical coordinates. Note that the Jacobian of the transformation to cylindrical coordinates is J r. Therefore, the volume can be calculated as =R 2 h " ;; ax 2 y 2 dxdy =R 2 h " ; S
2= R 2 ; ar rdr dt, where R 0 0
r a .
The remaining calculations in MuPAD are simple. reset(): // this is important, why? R : sqrt(h/a): Vol : PI*R^2*h-int(int(a*r^2*r, r0..R), t0..2*PI)
= h2 2a
Chapter 4 ( Multivariable claculus
163
For a 1 and h 9 we get LargePar : subs(Vol, a1, h9)
81= 2 The small paraboloid, for a 1 and h 4, will have the volume SmallPar : subs(Vol, a1, h4)
8= and the final volume is FialVolume : LargePar - SmallPar
65 = 2 As mentioned before, the problem presented here can also be solved using very simple means. It is enough to notice that after substituting y 0 into the equation of the surface, we obtain the curve z x 2 on the xz-plane and the bowl can be considered as a surface of the revolution of the curve about the z-axis. Its volume can be obtained using the formula
; 49 =xz 2 dz ; 49 = z 2 dz ; 49 =zdz
65 =. 2
Here
are
the
MuPAD
statements needed to plot the surface of the revolution and obtain the integral. The final graph parameters were adjusted in the Virtual Camera. reset(): z : x - x^2: A : plot::ZRotate(z(x), x4..9): B : plot::Curve3d([x,0,x^2], x4..9): plot(A, B, ScalingUnconstrained)
164
Getting started with MuPAD
int(PI*(sqrt(z))^2, z4..9)
65 = 2 Exercise 4.7 In problems 1 through 5, find the best way to visualize the solid bounded by the given surfaces. In each case, find the simplest method to calculate the volume of the solid. 1. z 6, z 2y, y x 2 and y 2 " x 2 2. z x 2 y 2 and z 5 " x 2 " y 2 3. x 2 y 2 1 and x 2 z 2 1 4. z 3x 2 2y 2 and z 5 " y 2 5. z
1 x 2 y 2
, z 1/2 and z 3
Algebra with MuPAD Depending on the level of mathematics we are dealing with, algebra consists of completely different topics. In high school algebra, we study polynomials and the transformation of algebraic expressions, whereas in university algebra we are concerned with concepts such as determinants, matrices, linear transformations, and so on. In this chapter, we introduce some of the most popular algebraic topics and discuss relevant MuPAD procedures that are useful in these algebraic investigations. The selection of topics for this chapter is not entirely accidental, but is far from complete.
5.1 1 Numbers and domains When solving problems in mathematics we may have different requirements. For example, when solving an equation, we may look for solutions that are real numbers, but on another occasion, we may be interested in complex solutions and at yet another time, in integer solutions. We therefore say that we solve an equation over the domain of real numbers, the domain of complex numbers, or the domain of integer numbers. In mathematics, the term ‘domain’ has several different meanings. For example, we frequently speak of a ‘domain of a function,’ where ‘domain’ means the set of elements for which the function is
166
Getting started with MuPAD
defined. When solving equations, we use it in a slightly wider sense, as a specific set of numbers, for example, the real or complex numbers. In abstract algebra, on the other hand, we use it to denote a set of objects with specific properties that is closed under some operations, for example a group of integers modulo p. In this section we concentrate on the second meaning of domain. The real domains in MuPAD, the domains in the last sense, we leave for another time. Let us consider the equation x 3 " 7x 6 0. MuPAD can easily produce the solutions of this equation. solve(x^3 - 7*x 6 0, x) {-3, 1, 2} However, we can ask MuPAD to restrict the solutions to a specific subset of real numbers, for example to x 0. To do so, we use the assume procedure. assume(x 0): solve(x^3 - 7*x 6 0, x) {1, 2} What happens if we assume another subset of x? assume(x 0): solve(x^3 - 7*x 6 0, x) {-3} or assume(x 1): solve(x^3 - 7*x 6 0, x) {-3, 1} Let us try another example. We will check what results are obtained when we solve the equation cos 2 x cos x over different domains. Before starting a new example, we should remove the previous assumptions since MuPAD still keeps them in memory. unassume(x): Now it is safe to declare a new equation and solve it. equation : (cos(x))^2 cos(x)
Chapter 5 ( Algebra with MuPAD
167
cosx 2 cosx solve(equation, x)
= =k 3 k i 2
: 2 = k 3 k i
The solutions presented in this form are difficult to understand. It would be easier to deal with them if we could get solutions over a given interval, for example over x ¡0, 20¢ or x ¡100, 110¢. Here they are. Note how we create a double assumption. First, we create the main assumption and then, with the statement assume(cond, _and), we extend it. That way we have restricted the calculations to a given interval. assume(x 0): assume(x 20, _and): solve(equation, x)
2 =, 4 =, 6 =, = , 3 = , 5 = , 7 = , 9 = , 11 = 2 2 2 2 2 2 assume(x 100): assume(x 110,_and): solve(equation, x)
32 =, 34 =, 65 = , 67 = , 69 = 2 2 2 There is another way of restricting calculations to a given interval. For this purpose, we can use a declaration of the Interval type. Let us check how it works and explain the mechanism later. unassume(x): assume(x, Type::Interval(PI,3*PI)): solve(equation, x)
2 =, 3 = , 5 = 2 2 In the above statement, we declared x as an element of the interval =, 3= . However, our requirements can be more sophisticated. The reader should analyze the next few lines and guess the assumptions about the variables made. assume(x, Type::Integer): solve(x^4 - 2/3 0, x)
K
168
Getting started with MuPAD
assume(x, Type::Real): solve(x^4 - 2/3 0, x)
"
4
18 4 3 , 3
4
18 4 3 3
assume(x, Type::Complex): solve(x^4 - 2/3 0, x)
"
4
18 4 3 , 3
4
18 4 3 , " 13 i 4 18 4 3 , 3
1 3
i 4 18 4 3
assume(x, Type::Imaginary): solve(x^4 - 2/3 0, x)
" 13 i 4 18 4 3 ,
1 3
i 4 18 4 3
In the last four examples, we asked MuPAD to produce solutions that are integers, real numbers, complex numbers or imaginary numbers. For this purpose, we used predefined types. MuPAD has a separate library of types. Here are some of them. Type::Arithmetical —arithmetical expressions, Type::Boolean—logical expressions, Type::Complex—complex expressions, Type::Constant—constants, Type::Even—even numbers, Type::Imaginary—imaginary numbers, Type::Integer—integer numbers, Type::Interval—interval of real numbers, Type::NegInt—negative integer numbers, Type::NegRat—negative rational numbers, Type::Negative—negative numbers, Type::NonNegInt—non-negative integers, Type::NonNegRat—non-negative rational numbers, Type::NonNegative—non-negative numbers, Type::NonZero—non-zero numbers, Type::Odd—odd numbers, Type::PosInt—positive integers, Type::PosRat—positive rational numbers,
Chapter 5 ( Algebra with MuPAD
169
Type::Positive—positive numbers, Type::RatExpr—rational expressions, Type::Rational—rational numbers, Type::Real—real numbers. We can obtain the complete list of types defined in MuPAD by executing the info(Type) statement. Before we finish this discussion, we should mention that we also have a library of domains in MuPAD. We can examine the contents of this library by executing the info(Dom) statement. It is worth noting that the concept of domains in MuPAD is very sophisticated and goes far beyond the scope of this book. The assume statement used in this section makes a permanent assumption about a given variable. It is likely, therefore, that we may forget about this assumption and later get incorrect results. We can avoid permanent assumptions by using a safer keyword, assuming. Assumptions made with assuming work only for a given command. In the next command, the assumptions are lifted. Let us examine a quick example. solve(x^4 - 2/3 0, x) assuming x0
"
4
18 4 3 3
solve(x^4 - 2/3 0, x)
"
4
18 4 3 , 3
4
18 4 3 , " 13 i 4 18 4 3 , 3
1 3
i 4 18 4 3
The assume statement and assuming keyword can also be mixed, allowing us to build more complex assumptions. Exercise 5.1 In problems from 1 through 5, solve the given equations over the real numbers, the positive real numbers, the integers and the complex numbers. 1. x 4 1 x 3 5 x 2 1 x " 2 0 2. x 4 x 2 " 20 0 3 6 4 2 3. x x 1 0
3
3
4. x 4 " x 2 " 1 0
5. z 2 1 " i 3 2i (In MuPAD, the imaginary unit i is denoted by I.)
170
Getting started with MuPAD
5.2 2 Complex numbers and quaternions Complex numbers are the default domain for many types of MuPAD calculations. This means that when solving equations, for example, MuPAD by default produces solutions that are complex numbers. Let us look at some examples. solve(x^2 1 0, x)
£"1 i, i¤ solve(x^3 1 0, x)
1 i 3, 2
"1, 1 " 2
1 i 3 1 2 2
solve(x^4 1 0, x)
" 12 " 12 i 2 , " 12 12 " 12 i 2 , 12
1 2 1 2
i 2 , i 2
As we see, all the solutions obtained are complex numbers. Complex numbers are a great topic in their right. We can declare them in MuPAD and then examine their properties. The easiest way of declaring a complex number is just to type it using the capital letter I as the imaginary unit. Below are the declarations of a few complex numbers. A : 3/7 7/3*I 3 7
7 3
i
B : -4/3 5/6*I
" 43
5 6
i
Now we can perform some operations on these numbers: AB, A-B, A*B, A/B
" 19 21
19 6
i,
37 21
3 2
i, " 317 " 347 126 126
i,
346 623
" 874 623
MuPAD can also calculate the modulus of a complex number: abs(A)
i
Chapter 5 ( Algebra with MuPAD
171
2482 441 From algebra courses we know that calculating the roots of complex numbers can be difficult. In MuPAD we can produce them quite easily if we know what to ask. Let us observe, in this context, that the standard function sqrt(A) does not make any sense and we know of course why. sqrt(A)
3 7 i 7 3 Instead of using sqrt, we can ask MuPAD to solve the equation x 2 " A 0. This is the method for producing the roots of complex numbers. solve(x^2 - A 0, x)
i "i
2482 42 2482 42
" "
3 14
3 14
2482 42
"
2482 42
3 14
,
3 14
In exactly the same way we can calculate the roots of any order n 1 of a complex number A, including A 1. Let us see how MuPAD calculates the cube roots of A 1. U : solve(x^3 - 1 0, x)
1, " 1 i 3 " 1 , 2 2
1 i 3 " 1 2 2
We have obtained a set of solutions of the equation x 3 " 1 0. Now we can take them out of the set U, assign each to a separate variable and calculate its trigonometric form as follows: x1 : U[1]
" 1 i 3 " 1 2 2 x2 : U[2]
1 i 3 " 1 2 2
172
Getting started with MuPAD
x3 : U[3] 1 x1 : rectform(x1)
3 "1 "i 2 2 x2 : rectform(x2)
3 "1 i 2 2 arg(x1), arg(x2)
"2=, 2= 3 3 This means that the obtained roots of 1 can be presented in trigonometric form (also known as polar form) as 3 x1 " 1 " i cos " 2 = 2 3 2 3 x2 " 1 i cos 2 = 2 2 3
i sin " 2 = 3 i sin 2 = 3
and, of course, x 3 1 cos 0 i sin 0 From a didactic point of view it might be useful to display the obtained roots on a graph and see where they are located in the complex plane. At the moment, MuPAD does not provide ready tools to visualize complex numbers directly. However, with our experience in graphics, we can easily complete this task. Below we present the minimal code needed to plot three points representing the complex numbers x 1 , x 2 and x 3 . We also plot a unit circle that helps us highlight the exact the locations of the points. Note that the presented code is a little rough. However, we will be able to develop a better method once we have become more familiar with MuPAD programming. A : plot::Point2d([Re(U[1]),Im(U[1])]): B : plot::Point2d([Re(U[2]),Im(U[2])]): C : plot::Point2d([Re(U[3]),Im(U[3])]): C1 : plot::Circle2d(1, [0,0]): plot(A,B,C,C1, PointSize3, PointColorRGB::Red)
Chapter 5 ( Algebra with MuPAD y
173
1.0 0.8 0.6 0.4 0.2
-1.0 -0.8 -0.6 -0.4 -0.2 -0.2
0.2
0.4
0.6
0.8
1.0
x
-0.4 -0.6 -0.8 -1.0
In our code we used two new elements. They were two the procedures Re and Im. We used them to extract the real and imaginary parts of a complex number. In this way, we were able to transform a complex number into a point in a plane. To get a more accurate plot, we should also change the name of the y-axis to i y. This can also be done in the Virtual Camera. Another useful graphical representation of complex numbers can be developed using vectors in a plane (the plot::Arrow2d class). The syntax of the arrow does not need an explanation and we have the following code: A : plot::Arrow2d([0,0],[Re(U[1]),Im(U[1])]): B : plot::Arrow2d([0,0],[Re(U[2]),Im(U[2])]): C : plot::Arrow2d([0,0],[Re(U[3]),Im(U[3])]): C1 : plot::Circle2d(1, [0,0]): plot(A,B,C,C1, PointSize3, PointColorRGB::Red) y
1.0 0.8 0.6 0.4 0.2
-1.0 -0.8 -0.6 -0.4 -0.2 -0.2
0.2
0.4
0.6
0.8
1.0
x
-0.4 -0.6 -0.8 -1.0
In many applications of complex numbers, we need the normal form of a complex number, in other words, the form |z|a bi , where |z| is the modulus of z and a 2 b 2 1. For this purpose, we can use the two
174
Getting started with MuPAD
procedures abs(z) and sign(z). The last procedure calculates
z . |z|
Finally, the rectform procedure, which presents a complex number in the form a bi, can also be very useful. Let us see these procedures in action. A : 3/2 2/3*I 3 2
2 3
i
abs(A) 97 36
sign(A) 9 97
4 97
i 97
rectform(%) 9 97 97
i
4 97 97
Complex numbers are fairly exotic numbers and many people have never heard about them. Quaternions are even more exotic. There are very few books and articles where we can read about them. MuPAD gives us ample opportunity to explore quaternions and investigate their properties. In general, a quaternion is a number of the form a b i c j d k, where a, b, c, d are real numbers and i, j and k are imaginary units that can be interpreted as three unit vectors, perpendicular to each other. In geometric terms, quaternions can be interpreted as points in 4D space with one real axis and three imaginary axes. In MuPAD, we can define quaternions using two different forms of syntax—by listing four numbers or by a polynomial-like expression. Let us declare two quaternions and see what we can do with them. a : Dom::Quaternion([2,5,-1,4])
25i"j4k b : Dom::Quaternion(3 3*i 6*j 7*k)
33i6j7k We can try some arithmetic operations.
Chapter 5 ( Algebra with MuPAD
175
ab, a-b
5 8 i 5 j 11 k, "1 2 i " 7 j " 3 k, 3*a - 4*b
"6 " 3 i " 27 j " 16 k a/b 43 103
40 103
i
8 103
j"
35 103
k
a^3
"819 " 201 i " 402 j " 469 k For quaternions, we can use some of the operations that we used for complex numbers. b : Dom::Quaternion(3 3*i 6*j 7*k)
33i3j7k Im(b)
3i6j7k Re(b) 3 conjugate(b)
3"3i"6j"7k abs(b)
103 sign(b)
3 103 103
3 i 103 6 103 j 7 103 k 103 103 103
In the last case, we obtained b . |b|
Quaternions are one of the most interesting types of numbers. It might be instructive for the reader gathering more information on quaternions, and then use MuPAD to investigate their properties.
176 Exercise 5.2
Getting started with MuPAD Let z 1 3 4i, z 2 "2 " 3i and z 3 4 " 2i.
1. Calculate z 1 z 2 z 2 , z 1 " z 2 , 3z 1 " z 2 2z 1 " z 3 . 2. Develop a graph presenting the numbers z 1 , z 2 , z 3 and the results obtained in exercise 1 as arrows. 3. Use MuPAD to convert z 1 , z 2 , z 3 to the polar form. 4. Calculate z 1 i and display it with z 1 on the same graph, using arrows to represent complex numbers. What is the angle between the arrows representing z 1 and z 1 i? Experiment with a few more complex numbers to check if your conclusion is correct. 5. Use MuPAD to investigate what the geometric effect is of dividing a complex number z by i. Check a few examples and formulate your conclusion. 6. Use MuPAD to investigate how quaternions are multiplied. For example, it is worthwhile checking what results we get from i j, j k, k j, and so on. An important question, for example, is whether the multiplication of quaternions is commutative.
5.3 3 Polynomials In various places in this book, we have already introduced basic operations on polynomials. To do so we used the informal definition of a polynomial. Let us see what we can do in MuPAD with polynomials defined this way. poly1 : x^3 - 13*x 12
x 3 " 13 x 12 poly2 : x^3 - 11*x^2 31*x - 21
x 3 " 11 x 2 31 x " 21 poly1*poly2
"x 3 " 13 x 12 "x 3 11 x 2 " 31 x 21 expand(%)
x 6 " 11 x 5 18 x 4 134 x 3 " 535 x 2 645 x " 252
Chapter 5 ( Algebra with MuPAD
177
factor(poly2)
x " 1 x " 7 x " 3 solve(poly20,x)
£1, 3, 7¤ factor(poly1/poly2)
x4 x"7 degree(poly1*poly2) 6 evalp(poly1, x2.1)
"6. 039 gcd(poly1,poly2)
x2 " 4 x 3 lcm(poly1,poly2)
x 4 " 7 x 3 " 13 x 2 103 x " 84 The approach presented here is convenient in simple situations. However, in more advanced calculations it is more convenient to use the formal definition of a polynomial. In this definition, we use the procedure poly where we specify the variable or variables of the polynomial. poly1 : poly(a*x^3 - 13*x 12,[x]) polya
x 3 " 13 x 12, ¡x¢
Observe how MuPAD sorts the terms of the polynomial, depending on the declared variables. In the following example, we declare a polynomial in the three variables x, y, and z. Two of them, x and y, we declare as variables of the polynomial, while the last one, z, was left undeclared. MuPAD therefore treats it as an unknown coefficient. poly2 : poly(x^2 x^3*y*z y^2*z^2 5*z3,[x,y]) polyz x 3
y x 2 z 2 y 2 5 z 3, ¡x, y¢
We will get a similar result if we only declare x or y as a variable of the polynomial. poly3 : poly(x^2 x^3*y*z y^2*z^2 5*z3,[x])
178 polyy
Getting started with MuPAD
z x 3 x 2 y 2 z 2 5 z 3, ¡x¢
poly4 : poly(x^2 x^3*y*z y^2*z^2 5*z3,[y]) polyz 2
y 2 x 3 z y x 2 5 z 3, ¡y¢
The poly2list procedure can be useful in many applications. It converts a polynomial into a list of coefficients and powers of the variable or variables. For example, when applying this procedure to poly1, the term ax 3 was converted to ¡a, 3¢. poly2list(poly1)
¡¡a, 3¢, ¡"13, 1¢, ¡12, 0¢¢ The structure of the output is somewhat more complex when we apply the poly2list procedure to polynomials in two or more variables. poly2list(poly2)
¡¡z, ¡3, 1¢¢, ¡1, ¡2, 0¢¢, ¡z 2 , ¡0, 2¢¢, ¡5 z 3, ¡0, 0¢¢¢ Let us also observe that in MuPAD we are not limited to polynomials with real or complex coefficients. We can build polynomials over any mathematical domain defined in MuPAD. For example, we can develop polynomials over integer numbers modulo 3, as in our next example. A : poly(x^3 11*x - 34,[x], Dom::IntegerMod(3)) polyx 3
2 x 2, ¡x¢, Dom::IntegerMod3
B : poly(x^4 21*x 17,[x], Dom::IntegerMod(3)) polyx 4
2, ¡x¢, Dom::IntegerMod3
AB polyx 4
x 3 2 x 1, ¡x¢, Dom::IntegerMod3
A*B polyx 7
2 x 5 2 x 4 2 x 3 x 1, ¡x¢, Dom::IntegerMod3
Exercise 5.3 In problems from 1 through 5, declare in MuPAD the given polynomials using the formal definition of polynomials, and check how MuPAD performs the operations , ", , /, factor, lcd, and lcm. 1. x 2 " 10x 21 and x 2 " 49
Chapter 5 ( Algebra with MuPAD
179
2. 142x 2 " 92x " 113x 3 49x 4 " 11x 5 x 6 24 and x 2 " 6x 5 3. 11x " 6x 2 x 3 " 6 and 74x " 15x 2 x 3 " 120 4. 945x " 522x 2 142x 3 " 19x 4 x 5 " 675 and 945y " 522y 2 142y 3 " 19y 4 y 5 " 675 5. 11xy " 5y " 22x 14x 2 " 2x 3 " 7x 2 y x 3 y 10 and xy " y " 2x 2, here both x and y are variables. 6. Declare the given polynomials 1-5 again, but this time over the domain of integers modulo 2. Check what results you get this time. How do these results differ from results obtained previously? 7. Repeat this exercise, declaring the above polynomials as polynomials over the domain of integers modulo 5. How do these results differ from those obtained in 6?
5.4 4 Systems of linear equations One of the most important topics in linear algebra is how to solve systems of linear equations. Using MuPAD, we can solve such systems using two procedures—the well-known universal procedure solve, as well as a more specialized linsolve procedure. We also have the library linalg containing procedures for dealing with various aspects of in linear algebra. The solve procedure uses general algorithms for solving equations. Therefore, for more complex problems this procedure may not be fast enough. The linsolve procedure uses special algorithms for solving systems of linear equations and sometimes can be much faster than solve. Let us explore some examples. equations : x - 2*y x y z 5*x - 3*y }
{ 3*z t 7, t 1, - 3*z 2
£t x y z 1, t x " 2y " 3z 7, 5x " 3y " 3z 2¤
180
Getting started with MuPAD
solve(equations, {x,y,z})
x 5 " 3 t , y 15 " 5 t , z 15 t " 57 8 8 2 2 8 8 We obtain the same result using the linsolve procedure. linsolve(equations, {x,y,z})
x 5 " 3 t , y 15 " 5 t , z 15 t " 57 8 8 2 2 8 8 Observe that the linsolve procedure gives us the opportunity to specify the order of calculating the solutions. This feature is important for some engineering calculations. linsolve(equations, [z,y,x])
z 15 t " 57 , y 15 " 5 t , x 5 " 3 t 8 8 2 2 8 8 The linsolve procedure can also be applied in examples that are not exactly systems of linear equations in x 1 , x 2 , . . . , x n . For example, we can use it to solve systems of functional equations with a linear structure. linsolve( {5*cos(x)3*exp(x) 1, cos(x)-2*exp(x) 0}, {cos(x), exp(x)} )
cos x 2 , e x 1 13 13 Another interesting application of the linsolve procedure is the solving of systems of linear equations over a specific domain. The example below shows how we can solve systems of linear equations over the domain of integers modulo 7. linsolve( {3*x 5*y 1, -2*x - 5*y 0}, {x,y}, Domain Dom::IntegerMod(7) )
¡x 1 mod 7, y 1 mod 7¢ MuPAD allows us to produce a graphical representation of a system of linear equations in at most three variables and determine whether or not the system has a solution. Let us examine how we can visualize the
Chapter 5 ( Algebra with MuPAD
181
solutions of a system of linear equations with three variables. In our example, we will use the system, 2z 1
x
y 4z 7 6x y
1
Each equation of the system represents a plane in 3D. Therefore, our main goal will be to plot three planes, together with a point that represents the solution of the system. To plot a plane, we can use the plot::Function3d class, provided that we can transform the equation of the plane into a function of the form z fx, y . This is impossible in the case of our last equation. Therefore, we use the plot::Plane class. The declaration of this class requires the coordinates of one point in the plane and a vector perpendicular to the plane—the so-called normal vector. Finding the coordinates of a point in a plane is easy. We have to substitute into the equations values for two of the variables and MuPAD will find the third. For instance, after substituting x 0 and y 0 into the equation x 2y 3z 6 we obtain z 3. Therefore, one of the points on the plane x 2y 3z 6 has the coordinates ¡0, 0, 3¢. Finding a normal vector for the given plane is even easier. We extract the coordinates of the normal vector from the equation of the plane. For example, the plane x 2y 3z 6 has the normal vector ¡1, 2, 3¢. Here is the code for our example. eq1 : x 2*z 1: eq2 : y 4*z 7: eq3 : 6*x y 1: linsolve({eq1,eq2,eq3}, {x,y,z})
x " 1 , y 4, z 3 4 2 // finding a point on each plane solve(subs(eq1, x0, y0), z) 1 2
solve(subs(eq2,x0, y0),z) 7 4
182
Getting started with MuPAD
solve(subs(eq3,x0, z0),y)
1 // declare planes and the point A : plot::Plane([0,0,1/2],[1,0,2]): B : plot::Plane([0,0,7/4],[0,1,4]): C : plot::Plane([0,1,0],[6,1,0]): P : plot::Point3d([-1/2,4,3/4]): plot(A,B,C,P)
In the obtained graph, the colors of the planes were changed in the Virtual Camera. Also, in the calculation of the planes, the values of the parameters UMesh and VMesh were reduced to 2. If, for some reason, a single solution of the system of linear equations does not exist, we do not have the point P, but can still plot the planes and find out why a solution does not exist or why we get multiple solutions. For example, when trying to solve the following system of linear equations, MuPAD fails. eq1 : x 3*y 2*z 1: eq2 : 2*x 6*y 4*z 7: eq3 : -x - 3*y - 2*z 3: linsolve({eq1,eq2,eq3}, {x,y,z}) FAIL The plot representing these three planes shows why such a solution does not exist —the planes are parallel.
Chapter 5 ( Algebra with MuPAD
183
Exercise 5.4 1. For each of the given systems of linear equations, where a, b and c are constants, obtain a solution. Find examples of values a, b, and c (if they exist), such that the system has one solution, infinitely many solutions or no solution at all. Visualize the system by giving a graphical explanation of what happens. a. x ay a, bx y b b. ax z 1, by z 1, x y c c. ax z 1, ay z 1, x y a, use animation to show how the solution changes, depending on the value of a. d. x 2y " 3z 4, 3x " y 5z 2, 4x ay z 2, use animation to show how the solution changes, depending on the value of a. 2. Use the methods you learned in this chapter to solve the given systems of nonlinear equations. a. x 2 y 2 z 2 6 2x 2 y 2 " z 2 3 x 2 " y 2 " 2z 2 2
184
Getting started with MuPAD b. x 2 y 2 z 2 3 x2 y2 " z2 3 x 2 " y 2 2z 2 2 c. sin x sin y sin z 2,
for x, y, z ¡0, 2=¢
2 sin x " 3 sin y " sin z 1 5 sin z 1
5.5 5 Declarations of matrices There are many ways of declaring matrices in MuPAD. For our purposes, we will use the most intuitive one in which we give the number of columns, number of rows, and a list of the rows of the declared matrix. matrix(3, 3, [[0,1,2], [1,0,3], [4,5,0]])
0 1 2 1 0 3 4 5 0 matrix(4, 4, [[0,1,2], [1,0,3], [4,5,0]])
0 1 2 0 1 0 3 0 4 5 0 0 0 0 0 0 matrix(4, 3, [[0,1,2], [1,0,3], [4,5,0]])
0 1 2 1 0 3 4 5 0 0 0 0 Observe that if we use incomplete rows, MuPAD will complete them by
Chapter 5 ( Algebra with MuPAD
185
adding the necessary zeros at the end of each incomplete row. With almost the same syntax, we can declare a number of special types of matrices. Here we show only a few examples. In each of these examples we declare the dimensions of the matrix and specify a single list of values that MuPAD uses different ways to create a matrix. matrix(4, 5, [5,3,2,5,8], Diagonal)
5 0 0 0 0 0 3 0 0 0 0 0 2 0 0 0 0 0 5 0 matrix(5, 5, [1,2,3,4,5,6,7,8,9], Banded)
5 6 7 8 9 4 5 6 7 8 3 4 5 6 7 2 3 4 5 6 1 2 3 4 5 matrix(5, 5, [5,3,3,5,8], Banded)
3 5 8 0 0 3 3 5 8 0 5 3 3 5 8 0 5 3 3 5 0 0 5 3 3 It may be convenient to declare a matrix using a function of two variables representing rows and columns. For example, the declaration below shows how we can declare a matrix using the function fn, m e nm . matrix(4, 4, (n,m) - exp(n m))
186
Getting started with MuPAD
e2 e3 e4 e5 e3 e4 e5 e6 e4 e5 e6 e7 e5 e6 e7 e8 A function in one or two variables can be useful for declaring a diagonal matrix. The remaining places in the matrix are filled with zeros. matrix(4, 4, n - exp(n), Diagonal)
e 0
0
0
2
0
0
0 0 e3
0
0 e
0 0
0 e4
Finally the hilbert procedure from the linalg library can help us create a Hilbert matrix of any dimension. Let us create a 5 5 Hilbert matrix. linalg::hilbert(5)
1 1 2 1 3 1 4 1 5
1 2 1 3 1 4 1 5 1 6
1 3 1 4 1 5 1 6 1 7
1 4 1 5 1 6 1 7 1 8
1 5 1 6 1 7 1 8 1 9
In many applications, it is useful to be able to create matrices with random data. For this purpose we may use the randomMatrix procedure from the linalg library. linalg::randomMatrix(5, 5, Dom::Integer)
Chapter 5 ( Algebra with MuPAD
337 "220 "502 "702 7 "942
187
109
281
"79
106
"11 "645
536
"327
41
"429
83 "679 "705 "476
"855
"33
189
66
582
We can declare random matrices over any domain restricted to a specific range. Here is an example of a random matrix consisting of integers 0 t n t 9. linalg::randomMatrix(4, 4, Dom::Integer, 0..9)
5 3 9 1 5 9 6 3 3 6 7 3 6 8 8 8 We can combine all these parameters into one declaration to produce special matrices. linalg::randomMatrix(6, 6, Dom::Integer, 0..100, Diagonal )
84
0
0
0
0
0
0
41
0
0
0
0
0
0
30
0
0
0
0
0
0
13
0
0
0
0
0
0
16 0
0
0
0
0
0
1
MuPAD contains many other ways of declaring matrices. For example, we can produce Vandermonde, Toeplitz or Pascal matrices. More information about these types of matrices can be found in MuPAD help.
188
Getting started with MuPAD
Exercise 5.5 1. Use the function fn, m n m ! to create a matrix 5 5. 2. Use the DIGITS:2 to produce a random matrix with floating point numbers (domain Dom::Float) with 2 significant digits. 3. Obtain random 5 5 matrices with complex entries, integer modulo 3 entries, and quaternions. 4. Use MuPAD help to find information about Pascal matrices. Develop a Pascal 10 10 matrix. 5. Use MuPAD help to find information about Vandermonde matrices. Create a 10 10 Vandermonde matrix with consecutive powers of a, starting with a 0 .
5.6 6 Visualization of matrices On some rare occasions, we may need to obtain a graphical representation of a matrix. The two plot classes plot::Matrixplot and plot::SparseMatrixplot can be useful for this purpose. In this book we will only discuss the first class. The plot::Matrixplot class produces a graph with points representing the entries of the matrix and a surface passing through these points. B : linalg::randomMatrix(5,5, Dom::Integer, -10..10)
"3 "10 "7
5
"10
2
7
7
"7
"6
8
0
1
"10
9
8
10
"9
7
"4
9
"2
6
7
6
Chapter 5 ( Algebra with MuPAD
189
plot(plot::Matrixplot(B))
The surface may be very smooth if we use the parameter InterpolationStyle Cubic. Another useful modification of this plot is to remove the surface patches from the plot. In this way, we obtain a rectangular net of lines and points.
5.7 7 Operations on matrices Now that we know how to declare matrices, we can investigate what kind of operations can be performed on them using MuPAD. We only show some of them below. Let us start be declaring a few simple matrices. A B C F
: : : :
matrix(3,3,[[7,6,0],[8,0,3],[6,1,9]]); matrix(3,3,[[9,7,0],[0,6,1],[0,0,8]]); matrix(2,3,[[7,1,7],[0,8,4]]); matrix(3,2,[[1,8],[7,5],[7,0]]);
Here are our matrices:
7 6 0 A
8 0 3 6 1 9
9 7 0 , B
0 6 1 0 0 8
,
190
Getting started with MuPAD
7 1 7
C
0 8 4
1 8 , F
7 5 7 0
Now we can start our experiments. A B
16 13
0
8
6
4
6
1
17
66 53
0
3*A 5*B
24 30 14 18
3
67
We can multiply matrices. However, as we know, this is not always possible. A*B
// this operation can be done
63 85
6
72 56 24 54 48 73 B*F
// this operations can be done also
58 107 49
30
56
0
F*B // this operations cannot be done Error: dimensions don’t match [(Dom::Matrix(Dom::ExpressionField()))::_mult]
Chapter 5 ( Algebra with MuPAD
191
We can produce an inverse matrix using the following syntax: A^(-1)
"
1 115 18 115 8 345
" "
18 115 21 115 29 345
6 " 115 7 115 16 115
This matrix contains fractions which we can convert globally to floating point numbers. float(A^(-1))
0. 008695652174
0. 1565217391 "0. 05217391304 "0. 1826086957
0. 06086956522
"0. 0231884058 "0. 08405797101
0. 1391304348
0. 1565217391
Another basic operation on matrices it to form their transpose. The procedure transpose from the linalg library will do this for us. linalg::transpose(A)
7 8 6 6 0 1 0 3 9 We can also perform a number of operations on matrices which we applied earlier to numbers and functions, such as diff(A,x), int(A,x)—differentiation or a term-by-term integration of a functional matrix. Some other operations are expand(A) and subs(A,xx0)—expanding or substituting terms into a matrix. In addition, MuPAD allows you to carry out two very interesting operations on matrices. They are map and zip. The map procedure applies a given function to all entries of a given matrix. Suppose that we have the function gx xe "3x . We can apply this function to all the terms of a matrix, as shown here: g : x - x*exp(-x*3); A : matrix([[7,6,0], [8,0,3], [6,1,9]]):
192
Getting started with MuPAD
map(A, g)
7 e "21 6 e "18
0
8 e "24
0
3 e "9
6 e "18
e "3
9 e "27
We can simplify the above statements by specifying the function as a parameter of the map procedure. map(A, x - x*exp(-x*3)) Now let us briefly consider the zip procedure. In order to see how zip works, let us define two matrices of the same dimension, together with a function of two variables. 7 6 0 A
8 0 3
9 7 0 ,B
0 6 1
6 1 9
, fx, y x y .
0 0 8
The zip procedure produces the matrix C in which each term is a value of the function fx, y , with x taken from matrix A and y from B. For example, the term C 1,1 fA 1,1 B 1,1 and 79 67 00 C
80 06 31 60 10 98
In MuPAD, we carry this operation out as follows: f : (x,y) - x*y: zip(A,B,f)
63 42
0
0
0
3
0
0
72
The zip operation can be a useful tool for creating new operations on matrices. For example, suppose that for two given matrices A and B, with integer entries, we wish to produce a new matrix containing the minimal
Chapter 5 ( Algebra with MuPAD
193
or maximal elements of A and B. This is how it is done: f : (x,y)-max(x,y): zip(A,B,f)
9 7 0 8 6 3 6 1 9 g : (x,y)-min(x,y): zip(A,B,g)
7 6 0 0 0 1 0 0 8 In exactly the same way, we can obtain the gcd of two matrices with integer or polynomial entries. h : (n,m) - gcd(n,m): zip(A,B,h)
1 1 0 8 6 1 6 1 1 The operations on matrices that we used in this chapter are global operations and we apply them to matrices as a whole. However, we can perform a number of local operations on matrices. These are, for example, operations used to manipulate rows and columns. You can find all these operations in the linalg library. We complete this chapter with a discussion the linalg::det procedure, used to calculate the determinants of square matrices.
194
Getting started with MuPAD
A : matrix(3,3,[[3, 2, 5],[-1, 5, 3],[1, 2, -5]])
3
2
5
"1 5
3
1
2 "5
linalg::det(A) -132 There is no doubt that the chapter devoted to applications of MuPAD in algebra should be much larger. However, the scope of this book does not allow us to go deeper into this topic. We therefore leave it to the reader to explore this subject further, as well as for possible sequel to this book. Exercise 5.7 1. Declare the following matrices in MuPAD. 1 2 3 A
2 3 1
0 2 3 ,B
3 2 1
2 0 1
0 2 3 ,C
3 2 0
1 0 3 1 2 0
Calculate with MuPAD (if this is possible): a. A B A C b. A B A C c. A B A C "1 d. A B C "1 e. map(A,f), where fx x 2 , f. map(B,f), where fx sinx= , g. zip(A,B,g), where gx, y x 2 y 2 h. obtain the determinants of the matrices A, B, C, as well as the other matrices produced in exercises a–g.
Data visualization and elementary statistics This chapter is somewhat experimental. While teaching my statistics course, I realized that MuPAD has a wonderful collection of tools for advanced statistics. However, many basic utilities for elementary statistics are still missing. Therefore, for this chapter I use some of the procedures that I had created for my classes. I also use the frequency procedure that was developed for me by Walter Oevel. This procedure will be a part of the next version of MuPAD. The names of my procedures may also change in the future if they are implemented in MuPAD. All procedures developed for this chapter can be downloaded from the book web site at http://majewski.mupad.com. Technical comment In order to make external procedures work with your installation of MuPAD, you have to: 1. Create a new folder for your files, such as D:\My Documents\mupad 2. Save the source files (*.mu) with the external procedures in this folder. For example, the files frequency.mu, statistics.mu, and so on. 3. In a MuPAD notebook, type in and execute the following commands:
196
Getting started with MuPAD
READPATH:"D:\\My Documents\\mupad": read("statistics.mu"): read("frequency.mu"): 4. Now, if you did not get any error messages, you can use any procedure included in the imported external files. For example, quantile([3,3,1,2,5,6,9],4,2).
6.1 1 Data formats In real life, data may have many different forms. However, in order to use them in MuPAD or any other program, we have to organize them in a structure that is understood by the program. In MuPAD, we have a number of ways to organize data. We can use lists, lists of lists, arrays, tables or the special structure stats::sample. In general, data should be organized in a kind of grid structure, so we can easily refer to each piece of data separately or extract some data such as extracting a range of rows or columns. An example of data organization is an Excel spreadsheet (see fig. 6.1).
Fig. 6.1 Data organized in Excel
Chapter 6 ( Data visualization and elementary statistics
197
In MuPAD, such data can be presented as a list of list, for example like here, data1 : [ ["Name","fat","sodium","carbo","sugar","rating"], ["Bran", 1, 130, 5, 6, 68], ["All_bran", 1, 260, 7, 5, 34], ["Cheerios", 2, 290, 17, 1, 51], ["Cocoa puffs", 1, 180, 12, 13, 23], ["Corn flakes", 0, 290, 21, 2, 36], ["Corn pops", 0, 90, 12, 12, 36], ["Crispix", 0, 220, 21, 3, 47], ["Frosted flakes", 0, 200, 14, 11, 31], ["Grains pecan", 3, 75, 13, 4, 46], ["Muesli", 3, 95, 16, 11, 37], ["Muesli II", 3, 150, 16, 11, 34], ["Oatmeal", 2, 170, 13.5, 10, 30], ["Wheaties", 1, 200, 17, 3, 52]] In simpler cases, a list such as the following might be enough. data2 : [130, 260, 290, 180, 290, 90, 220, 200, 75, 95, 150, 170, 200] Accessing particular data from a list or a list of lists can be done through appropriate indexes. For example, the statement data2[4] produces the fourth element of the list. data2[4] 180 In the case of a list of lists, we use two indexes. The first one gives us the access to a row. The second one to an element in the row. For example, data1[4] ["Cheerios", 2, 290, 17, 1, 51] data1[4][3] 290 The indexes, as well as the sequence operator, allow us to extract any range of data from a list or list of lists. This is how we extract the fourth column from data1. [data1[i][4] $ i1..nops(data1)]
198
Getting started with MuPAD
["carbo", 5, 7, 17, 12, 21, 12, 21, 14, 13, 16, 16, 13.5, 17] Usually, we prefer to work with uniform data such as data where all elements are of the same type. In such situations, we skip the labels for the data rows and columns. An alternative to data organized as a list of lists is an array. However, arrays must have a fixed number of rows and columns. Therefore, their use is somewhat restrictive. In MuPAD we also have a structure known as a table. It is similar to a list of lists or an array. However, when printing it on the screen, MuPAD typesets the table in a very clear way. Tables in MuPAD may grow as we develop them. Let us try to create a table, so we can better understand what it looks like and how it works. We will create a table from the data set data1 that was declared earlier. However, we will only use a small part of this data set, just the rows from 2 to 5. A : table( (idata1[i]) $ i2..5 ) 2 ["Bran",1,130,5,6,68], 3 ["All_bran",1,260,7,5,34], 4 ["Cheerios",2,290,17,1,51], 5 ["Cocoapuffs",1,180,12,13,23] The strange thing about MuPAD tables is that numbers and strings can be used as indexes and, at the same time, as labels for rows. For example, in the above output, the line 2["Bran",1,130,5,6,68] means that the entry of the table with label 2 is equal to ["Bran",1,130,5,6,68]. Here we are not talking about the second row of the table A. We are talking about the row that has the label 2. The number 2 is at the same time the index of the table entry and its label. Therefore, the statement A[1] produces noting, while A[2] produces the row labeled as a row 2.
Chapter 6 ( Data visualization and elementary statistics
199
A[2] ["Bran",1,130,5,6,68] Now we can add a new entry to table A, for example, an entry with the label M and the value [abcd,1234]. This may look strange, but this is how it works. A[M] : ([abcd,1234]): A 2 ["Bran",1,130,5,6,68], 3 ["All_bran",1,260,7,5,34], 4 ["Cheerios",2,290,17,1,51], 5 ["Cocoapuffs",1,180,12,13,23],
M ["abcd",1234] In each of the data structures described here, the statement nops(A) produces the number of elements in a given structure. For example, nops(A), nops(data1), nops(data2) 5, 14, 13 Entering a large amount of data in MuPAD can be a very tedious task. Usually, we already have the data in a spreadsheet or a text file. Therefore, before we move on to the next topic, it will be useful to find out how we can import data from Excel or another program into MuPAD. Observe that any software used for entering large amounts of data has built-in export options for some common formats. For example, Excel can save its workbooks in several HTML formats, the XML format, the CSV format, and so on. Let us concentrate on one of them, for example, on the CSV (comma delimited) format. This is a very simple ASCII format where the data is saved in rows, and the consecutive entries in each row are separated by the comma symbol “,”. Let us save the file shown in fig. 6.1 in Excel. We will save it in the CSV format and call it Book1.csv. Now, let us return to MuPAD. There we have the procedure import::readdata. This procedure can import data from a file into MuPAD. Each row of the data file is interpreted as a list, and we will obtain data in the form of a list of lists. We should specify the character that separates the data, otherwise, by default, MuPAD uses the space character. We must also remember that the readdata procedure looks
200
Getting started with MuPAD
for our data file in the location specified in the READPATH variable. So, for example, in our setting, specified at the beginning of this chapter, we must save the data file in the folder c:\My Documents\mupad\. The command to import Book1.csv into MuPAD may have the following form: data3 : import::readdata("Book1.csv",",") [[Name, fat, sodium, carbo, sugar, rating], [Bran, 1, 130, 5, 6, 68], [All - bran, 1, 260, 7, 5, 34], [Cheerios, 2, 290, 17, 1, 51], ["Cocoa puffs", 1, 180, 12, 13, 23], ["Corn flakes", 0, 290, 21, 2, 36], ["Corn pops", 0, 90, 12, 12, 36], [Crispix, 0, 220, 21, 3, 47], ["Frosted flakes", 0, 200, 14, 11, 31], ["Grains pecan", 3, 75, 13, 4, 46], [Muesli, 3, 95, 16, 11, 37], ["Muesli II", 3, 150, 16, 11, 34], [Oatmeal, 2, 170, 13.5, 10, 30], [Wheaties, 1, 200, 17, 3, 52]] Observe that there is one ‘feature’ of this procedure. Some of the text entries were converted properly into a string of characters, but some others were not. Therefore, we will need a procedure to clean up the imported data and to convert all the entries that are not numbers into strings. This is a nice exercise for the programming chapter. Exercise 6.1 1. In My Documents create a new folder and call it mupad. Save in this folder one or two MuPAD *.mu files (you can download them from http://majewski.mupad.com). Declare the READPATH variable so it points to the newly created folder. Check if you can read any of the files using the read procedure. This exercise is essential for the rest of this chapter. So repeat it until you are sure that everything works perfectly. 2. In Excel, type in the table below. Save it as the CSV file days.csv in the folder in My Documents\mupad. Use the import::readdata procedure to import days.csv in MuPAD. Assign data from the
Chapter 6 ( Data visualization and elementary statistics
201
days.csv file to a variable called days. day in Hong Kong temperature humidity rain Mon 21.07
29. 0
90
21
Tue 22.07
26. 5
96
16
Wed 23.07
25. 2
97
5
Thu 24.07
23. 2
98
12
Fri 25.07
23. 5
98
6
Sat 26.07
28. 3
96
1
Sun 27.07
27. 4
99
12
3. Extract from the days variable the temperature column and assign it to a new variable temperature. Note that for further applications it is sometimes convenient to ignore the header of the column. How we can do this? 4. Convert the days data into a table with the labels Mon, Tue, .. , Sun and assign it to a new variable daysTable. Ignore the dates for each day. Ignore also the headers for each column. 5. Extract from the daysTable the humidity information and assign it to a new variable called humidity.
6.2 2 Plotting tabulated data There are a number of ways of plotting data in MuPAD. We can use bars, piecharts and a few other methods. In this section we will explore some of them. Let us return to our data3. We will extract some columns from this data set. Here they are: fat : [data3[i][2] $ i2..nops(data3)] [1, 1, 2, 1, 0, 0, 0, 0, 3, 3, 3, 2, 1] sodium : [data3[i][3] $ i2..nops(data3)] [130, 260, 290, 180, 290, 90, 220, 200, 75, 95, 150, 170, 200] carbo : [data3[i][4] $ i2..nops(data3)]
202
Getting started with MuPAD
[5, 7, 17, 12, 21, 12, 21, 14, 13, 16, 16, 13.5, 17] sugar : [data3[i][4] $ i2..nops(data3)] [5, 7, 17, 12, 21, 12, 21, 14, 13, 16, 16, 13.5, 17] rating : [data3[i][5] $ i2..nops(data3)] [6, 5, 1, 13, 2, 12, 3, 11, 4, 11, 11, 10, 3] Now we try to produce a single plot for each of these sets or for a collection of some of them. The graph, called a bar chart, with bars running horizontal for the sodium variable, can be obtained as follows. sodiumBar : plot::Bars2d(sodium): plot(sodiumBar) y
300
200
100
0 0
1
2
3
4
5
6
7
8
9
10
11
12
x
A similar plot, but this time using thin horizontal bars for the carbo variable, uses the additional parameters DrawModeHorizontal and BarStyleLinesPoints. carboBar : plot::Bars2d(carbo, DrawModeHorizontal, BarStyleLinesPoints ): plot(carboBar)
Chapter 6 ( Data visualization and elementary statistics
203
y 12
10
8
6
4
2
0 0
2
4
6
8
10
12
14
16
18
20
x
To each of these graphs we can add grids and a few other elements to enhance their readability. This can easily be done with the Virtual Camera. Note that at the moment we do not have a plot class in MuPAD for producing a line graph for a list of data. However, we can use the plot::Polygon2d class for this purpose. First we produce a list of points and then we plot a polygon joining the points. sugarPoints : [[i,sugar[i]] $ i1..nops(sugar)] [[1,5], [2,7], [3,17], [4,12], [5,21], [6,12], [7,21], [8,14], [9,13], [10,16], [11,16], [12,13.5], [13,17]] sugarPlot : plot::Polygon2d(sugarPoints, GridVisibleTRUE, YSubgridVisibleTRUE ): plot(sugarPlot) y 20 18 16 14 12 10 8 6 1
2
3
4
5
6
7
8
9
10
11
12
13
x
204
Getting started with MuPAD
Note that none of these types of graphs allows us to use our own labels. Therefore, the numbers 1, 2, 3, . . , 13 on the x-axis (or y-axis for horizontal bars) should be understood as shortcuts for the name of the product. Here 1 means bran, 2 means all-bran, and so on. In cases where the data form different parts of the same thing, we can use the piechart plot. For example, suppose that for our favorite red curry, we use 2 units of ginger, 2 of cumin, 2 of coriander, 2 of sweet paprika, 3 of chili powder, 5 of tomato paste, and 3 cloves of garlic (do not try this mix, it may be too hot for you). Here the unit may be understood to be a teaspoon or a tablespoon, depending on the quantity of food. We can use a piechart to obtain a plot showing the percentage of each spice in the whole mix. In MuPAD, we declare two lists, one for numbers and one for labels, and then we plot both of them. spices : [2, 2, 2, 2, 3, 5, 3] [2,2,2,2,3,5,3] labels : ["ginger","cumin","coriander","paprika", "chili", "tomato", "garlic"] ["ginger", "cumin", "coriander", "paprika", "chili", "tomato", "garlic"] spicesPlot : plot::Piechart2d(spices, Titleslabels ): plot(spicesPlot) coriander cumin
paprika
ginger chili
garlic
tomato
Chapter 6 ( Data visualization and elementary statistics If we wanted to create plot::Piechart3d class.
a
fancier
plot,
we
could
205 use
the
In some situations, it is useful to have a graph plotting data sorted from the largest to the smallest values and display them in a form where it is easy to locate the largest values. For example, suppose that we are counting car accidents in a city. We would like to be able to identify the places where the number of accidents is highest so that the city council knows where they need to improve the traffic conditons. Let us put this data into an Excel file (see fig. 6.2), export it to a CSV file, and then import the result into MuPAD.
Fig. 6.2 Table of accidents In MuPAD, we type the following statement. data4 : import::readdata("accidents.csv",","): Then we remove the first row of labels from data4 data set. data4 : [data4[i] $ i2..nops(data4)] Finally, we plot the pareto diagram (Use here the pareto procedure from the statistics.mu collection mentioned). plot(pareto(data4))
206
Getting started with MuPAD
y
18 16 14 12 10 8 6 4 2 0
8 th
3rd
d
t
7 th
2n
1s
5 th
6 th
4 th
x
With the help of the pareto graph, the city council will have no trouble noticing that the 4th and 6th streets are the major trouble spots, and if they improve the traffic conditions on these streets, the number of accidents in the city may go down significantly. In order to plot multiple lists of data, we can use the same plot::Bars2d or plot::Bars3d classes. For example, let us plot the fat, sugar, carbo and rating data sets on one graph. allInOne : plot::Bars2d([fat, carbo, sugar, rating]): plot(allInOne) y 20
15
10
5
0 0
10
20
30
40
50
x
Chapter 6 ( Data visualization and elementary statistics
207
Note that the horizontal scale in this plot make no sense. It would be good to be able to place labels there for each data set, and separate each set from the next one. In the best case scenario, it might be appropriate to remove the numbers and the ticks for the x-axis using the Virtual Camera. The next plot shows some possible improvements in this graph. y
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
x
Another version of the same graph can be a 3D graph, where the data is presented as a box in 3D space. allInOne : plot::Bars3d( [fat, carbo, sugar, rating]): plot(allInOne)
208
Getting started with MuPAD
In this graph, many other improvements are possible. Some of them can be achieved with the Virtual Camera, but some others will have to wait for a new version of MuPAD.
Exercise 6.2 1. From the daysTable data set (see exercise 6.1) extract the temperature, humidity and rain columns, and assign them to variables with the names temp, hum and rain respectively. 2. For each of these variables produce the bars 2d plot to display the amount of rain and humidity, and the temperature for each day. Obtain the linear graphs for these data. How would you obtain a graph where we display linear graphs for each of these data in the same coordinate system? 3. Produce a piechart for the rain data to show the percentage of rain each day of the total weekly rainfall. 4. How would you obtain a linear graph that displays the cumulative rainfall for the whole week (each day should show the total amount of rain from the beginning of the week to this day)? 5. Obtain a plot where all these three data sets are displayed in the same coordinate system. Use bars 2d and bars 3d to display your data sets.
Chapter 6 ( Data visualization and elementary statistics
209
6.3 3 Frequency distributions Raw statistical data is usually a collection of numbers or strings organized in the form of lists or tables. Usually, our first requirement is to find the range of data, the smallest and the largest values. Sometimes we also want to sort the data so that we have a rough idea of its distribution. Then we usually want to find out how frequently some of the data occurs in the data set, or even visualize them somehow. Let us start by creating a raw data set. This will be a list with the ages of people in a building. ageList 80, 59, 71, 51, 33, 49, 39, 31, 23, 20,
: [52, 19, 36, 9, 7, 3, 75, 63, 52, 39, 47, 73, 81, 37, 52, 63, 69, 7, 47, 50, 48, 18, 39, 5, 43, 30, 43, 40, 28, 29, 25, 23, 31, 45, 50, 37, 39, 40, 31, 50, 23, 33, 29, 32, 50, 27, 21, 41, 41, 33, 42, 34, 24, 33, 20, 38, 26, 33, 23, 29, 48, 20, 41, 31, 47]
Now we can easily find the range of the ages of these people. min(ageList) 3 max(ageList) 81 From the list, we can also find out how many people live in the building. nops(ageList) 75 Now we know that the youngest person is only 3 years old and the oldest is 81. We know also that there are 75 people in the building. If we sort the data, we are able to see how many people are in each age group. sort(ageList) [3, 23, 31, 39, 47, 59,
5, 7, 7, 9, 24, 25, 26, 32, 33, 33, 39, 39, 40, 47, 48, 48, 63, 63, 69,
18, 27, 33, 40, 49, 71,
19, 28, 33, 41, 50, 73,
20, 29, 33, 41, 50, 75,
20, 29, 34, 41, 50, 80,
20, 29, 36, 42, 50, 81]
21, 30, 37, 43, 51,
23, 31, 37, 43, 52,
23, 31, 38, 45, 52,
23, 31, 39, 47, 52,
210
Getting started with MuPAD
From the sorted data, we can work out that the children in the building form the smallest group and there is quite large number of middle age people. A good visual representation of this data set can be the so-called dot plot, which presents all data in the form of points and shows how frequently each age occurs in the data set. We use the dotPlot procedure from the statistics.mu collection to do so. This procedure is not a part of MuPAD 3.1. plot(dotPlot(ageList, 0, 85)) y
5
4
3
2
1
0 0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
x
The plot shows that in the building, the group of inhabitants between 28 and 45 is quite significant. The group of children, as well as the group of old people, are both very small. Even a very good dot plot may not be enough to visualize a data set with thousands or millions of numbers. Moreover, the dot plot produces a picture, but does not produce numbers representing the frequency of the data. Therefore, we may need a more sophisticated tool to depict the frequency of the data. Before talking about this type of tool, it is important to discuss how we can group data. It is obvious that large data sets should be split into multiple groups, which we will call classes. For example, while taking about the age of people, we usually talk about babies (age between 0 and say 3), small children (age 4 through 6), elementary school students (age 7 through 10), and so on. Although the grouping generally destroys much of the original
Chapter 6 ( Data visualization and elementary statistics
211
detail of the data, we get a clearer overall picture of the data set. It is important to note that depending on the size of the classes, we may get more or less accurate information. Let us remind ourselves of some basic terms related to classes. Suppose that we are talking about age. The symbols 0. . 3, 4. . 6, 7. . 10 are called class intervals. The numbers 0 and 3, 4 and 6, are called class limits—the smaller number is the lower class limit and the larger the upper class limit. We may also consider classes that do not have a lower class limit or upper class limit. However, in many applications this is impractical. For example, how can we talk about people’s age, considering a class without an upper limit? We can consider a group of people aged 70 years and over, but there is still an upper limit for this group. Note that in our definition, there are gaps between the classes. Therefore, we prefer to consider slightly larger intervals. For example, instead of using the classes 4. . 6 and then 7. . 10, we use 3. 5. . 6. 5 and 6. 5. . 10. 5. The numbers 3. 5, 6. 5, 10. 5 are the true class limits, or class boundaries. Many authors require that class boundaries do not coincide with actual observations. By class size or class width we mean the difference between the upper class boundary and the lower class boundary. For example, for the class 3. . 6, the class width is 6. 5 " 3. 5 3. A class mark is the midpoint of the class. For the class 3. . 6, this is 6 " 3 /2 3 . 2
Technical comment In this chapter, while talking about classes, we will symbolize and define them using boundaries (not upper and lower class limit), and we will require that our observations do not coincide with class boundaries. In order to be consistent throughout the book, we will declare classes using only one method—the range operator a..b. for example, 0..5 for the class with the lower boundary 0 and the upper boundary 5. Let us return to MuPAD. In our example, the ageList data set contains data between 3 and 81. Therefore it is convenient to consider all classes to be equal in size, say 5 or 10, with the lowest class limit equal to 0, and the last class containing 81. We can create such classes using the list operator. For example, something like the following would be almost perfect for our example.
212
Getting started with MuPAD
clasSize : 5: startFrom : 0: endOn : max(ageList) div clasSize: ageClasses : [ startFromclasSize*i..startFromclasSize*(i1) $ i0..endOn ] [0..5, 5..10, 10..15, 15..20, 20..25, 25..30, 30..35, 35..40, 40..45, 45..50, 50..55, 55..60, 60..65, 65..70, 70..75, 75..80, 80..85] The same code, with class size equal to 10, produces another set of classes. [0..10, 10..20, 20..30, 30..40, 40..50, 50..60, 60..70, 70..80, 80..90] Observe that the result obtained in this way does not satisfy with our earlier requirement. The class boundaries coincide with the numbers on the age list. Therefore, it is necessary to shift them down about 0. 5 units: clasSize : 10: startFrom: 0-0.5: endOn : max(ageList) div clasSize: ageClasses10 : [ startFromclasSize*i..startFromclasSize*(i1) $ i0..endOn ] [-0.5..9.5, 9.5..19.5, 19.5..29.5, 29.5..39.5, 39.5..49.5, 49.5..59.5, 59.5..69.5, 69.5..79.5, 79.5..89.5] clasSize : 5: startFrom : 0-0.5: endOn : max(ageList) div clasSize: ageClasses5 : [ startFromclasSize*i..startFromclasSize*(i1) $ i0..endOn ] [-0.5..4.5, 19.5..24.5, 39.5..44.5, 59.5..64.5, 79.5..84.5]
4.5..9.5, 9.5..14.5, 14.5..19.5, 24.5..29.5, 29.5..34.5, 34.5..39.5, 44.5..49.5, 49.5..54.5, 54.5..59.5, 64.5..69.5, 69.5..74.5, 74.5..79.5,
Chapter 6 ( Data visualization and elementary statistics
213
Each of the obtained results fits our needs perfectly. Now we can investigate the frequency of the data in ageList with respect to the formulated classes. For this purpose, we use the stats::frequency procedure. Note that this procedure is not a part of MuPAD 3.1, so you need to download it from the book web site. stats::frequency(ageList, ageClasses10)
1 2 3 4 5 6 7 8 9
0.5, 9.5 , 5, 3, 5, 7, 7, 9 9.5, 19.5 , 2, 18, 19 19.5, 29.5 , 16, 20, 20, 20, 21, 23, 23, 23, 23, 24, 25, 26, 27, 28, 29, 29, 29 29.5, 39.5 , 20, 30, 31, 31, 31, 31, 32, 33, 33, 33, 33, 33, 34, 36, 37, 37, 38, 39, 39, 39, 39 39.5, 49.5 , 15, 40, 40, 41, 41, 41, 42, 43, 43, 45, 47, 47, 47, 48, 48, 49 49.5, 59.5 , 9, 50, 50, 50, 50, 51, 52, 52, 52, 59 59.5, 69.5 , 3, 63, 63, 69 69.5, 79.5 , 3, 71, 73, 75 79.5, 89.5 , 2, 80, 81
The obtained result is a modified version of a graph known from elementary statistics as a stem-and-leaf diagram, and presents essentially the same information. Each row in this output contains the class boundaries, the class frequency and the data in this class, listed in ascending order. The same procedure for smaller classes, with class width equal to 5, produces completely different results. stats::frequency(ageList, ageClasses5)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
0.5, 4.5 , 1, 3 4.5, 9.5 , 4, 5, 7, 7, 9 9.5, 14.5 , 0, 14.5, 19.5 , 2, 18, 19 19.5, 24.5 , 9, 20, 20, 20, 21, 23, 23, 23, 23, 24 24.5, 29.5 , 7, 25, 26, 27, 28, 29, 29, 29 29.5, 34.5 , 12, 30, 31, 31, 31, 31, 32, 33, 33, 33, 33, 33, 34 34.5, 39.5 , 8, 36, 37, 37, 38, 39, 39, 39, 39 39.5, 44.5 , 8, 40, 40, 41, 41, 41, 42, 43, 43 44.5, 49.5 , 7, 45, 47, 47, 47, 48, 48, 49 49.5, 54.5 , 8, 50, 50, 50, 50, 51, 52, 52, 52 54.5, 59.5 , 1, 59 59.5, 64.5 , 2, 63, 63 64.5, 69.5 , 1, 69 69.5, 74.5 , 2, 71, 73 74.5, 79.5 , 1, 75 79.5, 84.5 , 2, 80, 81
214
Getting started with MuPAD
By analyzing both results we can see that the one with the larger classes (class width equal 10) summarizes the information quite well, whereas the second result produces more detailed information, but becomes a little messy because it includes too many classes with a small amount of data. The frequency for the ageList can also be presented in a more visual form. We will get a picture representing our data, but will again lose some detail. To visualize the ageList data set, we will use the plot::Histogram2d class. ageHist10 : plot::Histogram2d( ageList, CellsageClasses10 ): plot(ageHist10) y
20
15
10
5
0
0
10
20
30
40
50
60
70
80
90
x
For smaller classes, we get the following histogram: ageHist5 : plot::Histogram2d( ageList, CellsageClasses5 ): plot(ageHist5) y
12
10
8
6
4
2
0
0
10
20
30
40
50
60
70
80
x
Chapter 6 ( Data visualization and elementary statistics
215
Again we see that the histogram for smaller classes shows much more detailed information, but is less convincing because it includes many classes with low frequency. The plot::histogram2d class has interesting properties that are worth knowing. In the two obtained graphs, the y-axis represents the real frequency for each class. However, in some applications we may be interested in displaying, on the y-axis, the so-called frequency density, that is to say, the area of the class bar equal to the class frequency, and the total area of the graph equal to the total frequency; or the relative frequency, the values on the y-axis that show the percentage of the given class as part of the total frequency. In MuPAD, we can produce both types of histograms by using the additional parameter Area. Using Area equal total frequency we obtain the frequency density plot, whereas with Area1 we obtain the relative frequency plot. totalFreq : nops(ageList): ageDensityHist10 : plot::Histogram2d(ageList, CellsageClasses10, AreatotalFreq ): plot(ageDensityHist10) y
2 .0
1 .5
1 .0
0 .5
0 .0 0
10
20
30
40
50
60
70
80
90
x
ageRelativeHist10 : plot::Histogram2d(ageList, CellsageClasses10, Area1 ): plot(ageRelativeHist10)
216
Getting started with MuPAD
y 0.025
0.020
0.015
0.010
0.005
0.000 0
10
20
30
40
50
60
70
80
90
x
The area under the histogram is equal to 1. 0, and this feature of the relative frequency histogram can be useful for comparing two different data sets. Suppose that we wish to compare the population of building 1 (ageList) with population of building 2 (ageList2). ageList2 : [41, 19, 72, 21, 11, 55, 7, 3, 25, 35, 23, 3, 19, 40, 57, 5, 29, 56, 24, 47, 38, 42, 20, 26, 20, 23, 45, 35, 22, 33, 27, 20, 33, 46, 29, 33, 48, 40, 31, 42, 38, 40, 37, 25, 50, 23, 41, 30, 22, 45, 42, 39, 48, 26, 31, 28, 47, 24, 38, 27] We can compare both data sets using the double dot plot diagram. Here we are using the dotPlotDouble procedure from the statistics.mu collection. This procedure is not a part of MuPAD 3.1. plot(dotPlotDouble(ageList, ageList2, 0, 85)) y
5 4 3 2 1 0 5 -1 -2 -3
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
x
Chapter 6 ( Data visualization and elementary statistics
217
However, this plot does not allow a correct comparison of the two populations since one of them is much smaller. For example, suppose that, for each building, we wish to find out what the percentage of people in the range 20 to 50 is. For this purpose, we can use relative histograms. ageRelativeHist10 : plot::Histogram2d(ageList, CellsageClasses10, Area1, ViewingBoxYMax0.035 ): ageRelativeHist10b : plot::Histogram2d(ageList2, CellsageClasses10, Area1, ViewingBoxYMax0.035 ): S1 : plot::Scene2d(ageRelativeHist10): S2 : plot::Scene2d(ageRelativeHist10b): plot(S1, S2) y
y 0.03
0.03
0.02
0.02
0.01
0.01
0.00
0.00 0
20
40
60
80
x
0
20
40
60
80
x
From the right graph we can see that the percentage of people in the range 20. . 50 in the second building is much higher than in the first building. Finally, for some data sets it is useful to produce a cumulative frequency plot, such as the one below for ageList with ageClasses10. Developing such a plot can be simple. We therefore leave this activity to the readers.
218
Getting started with MuPAD
y 70 60 50 40 30 20 10 0 0
10
20
30
40
50
60
70
80
90
x
Fig. 6.4 Cumulative frequency plot for ageList Exercise 6.3 For this exercise, we use two data sets containing the grades from a mathematics exam in two different classes. One of the classes is larger than the other. The results are also different. gradesList [28, 35, 73, 37, 63, 35, 39, 20, 80, 78, 25, 28, 50, 68, 49, 37, 23, 23, 76, 22, 42, 61, 71, 21, 33, 38, 39, 23, 56, 78, 70, 27, 76, 77, 25, 78, 53, 68, 44, 50, 71, 26, 36, 61, 28, 75, 55, 23, 42, 39] gradesList2 [59, 96, 59, 74, 67, 89, 100, 77, 50, 96, 40, 87, 54, 49, 85, 70, 94, 47, 77, 67, 93, 92, 64, 97, 43, 55, 40, 89, 100, 92] 1. For each of these data sets, obtain its minimum and maximum grade, and find out how many students are in each class. Decide on the size of classes that are appropriate for these data. For example, a good choice of the classes is the one that reflects the letter grade scale: A, A, A-, B, B, ... . 2. Declare a common set of classes for both data sets. 3. Obtain the frequency table for each data set. Can you conclude which class performed better during the exam?
Chapter 6 ( Data visualization and elementary statistics
219
4. Obtain a separate dot plot for each of the data sets and a double dot plot to compare the two classes. 5. Obtain histograms and relative histograms for both classes. Compare the two classes using relative histograms and decide which class, in your opinion, did a better job on the exam.
6.4 4 Measures of central tendency Until now, we have concentrated on the visualization of data. In this section, we will show how to calculate some major characteristics of data and will express the spread of the data with the help of formulas and numbers. When dealing with numerical data, we may need to calculate the sum of all data or various types of averages. Most of these things can be done without even a basic knowledge of programming. Let us look back at the ageList data set and calculate the sum of all of its data. ageList 80, 59, 71, 51, 33, 49, 39, 31, 23, 20,
: [52, 19, 36, 9, 7, 3, 75, 63, 52, 39, 47, 73, 81, 37, 52, 63, 69, 7, 47, 50, 48, 18, 39, 5, 43, 30, 43, 40, 28, 29, 25, 23, 31, 45, 50, 37, 39, 40, 31, 50, 23, 33, 29, 32, 50, 27, 21, 41, 41, 33, 42, 34, 24, 33, 20, 38, 26, 33, 23, 29, 48, 20, 41, 31, 47]:
The command nops(ageList) produces for us the number of data in the ageList. This number can be used later as a limit for the sum. nops(ageList) 75 The sum of the data in the ageList can be expressed as 52 19 . . . 47 ageList¡1¢ ageList¡2¢ . . . ageList¡75¢
75 ageList¡i¢ ! i1
In MuPAD, we would express the last formula as follows: S : sum(ageList[i], i1..75) 2850 or even as
220
Getting started with MuPAD
S : sum(ageList[i], i1..nops(ageList)) 2850 Calculating the arithmetic mean x 1
75
75 ageList¡i¢, of all data in the ! i1
ageList is now a simple task. meanAge : sum( ageList[i],i1..nops(ageList) )/nops(ageList) 38 We could get the same result using the stats::mean(ageList) command, but sometimes it is useful to do things from scratch. Using a similar technique, we can obtain a number of other characteristics, for example, the weighted arithmetic mean. Before we do so in MuPAD, let us recall what a weighted arithmetic mean actually is. Sometimes we associate with the data x 1 , . . , x N certain weighting factors, w i , . . , w N , depending on the importance of the numbers. The weighted arithmetic mean can then be expressed by the formula x
x 1 w 1 x 2 w 2 . . . x N w N w 1 w 2 . . w N
N x w ! i1 i i N w ! i1 i
To recreate this formula in MuPAD, we first have to declare our data, as well as the weighting factors: data : [46.4, 22.2, 66.1, 68.8, 5.7, 94.2, 11.0, 52.3, 74.1, 80.7, 49.5, 84.2, 26.3, 72.8, 66.0, 48.3, 62.7, 19.1, 34.6, 42.9, 42.7, 17.0, 30.8, 41.8, 75.6, 61.8, 94.5, 96.4, 17.8, 86.7]: and factors:[18, 12, 5, 6, 14, 4, 5, 19, 15, 1, 9, 1, 0, 2, 6, 13, 14, 11, 16, 18, 4, 6, 7, 20, 9, 19, 18, 8, 20, 7]: We can now obtain the weighted mean by executing the statement sum( data[i]*factors[i], i1..nops(data) )/sum(factors[i], i1..nops(data))
Chapter 6 ( Data visualization and elementary statistics
221
49.7 In many applications it is important to calculate the median or the mode of a data set. Again, let us recall what the median and the mode of a data set are. The median of a data set, arranged in order of magnitude, is either the middle value or the arithmetic mean of the two middle values. The mode of a data set is the value that occurs most frequently. To calculate the median, we have to sort our data first and check if we have an even or odd set of numbers. Then we can obtain the median. ageList : sort(ageList) [3, 23, 31, 39, 47, 59,
5, 7, 7, 9, 24, 25, 26, 32, 33, 33, 39, 39, 40, 47, 48, 48, 63, 63, 69,
18, 27, 33, 40, 49, 71,
19, 28, 33, 41, 50, 73,
20, 29, 33, 41, 50, 75,
20, 29, 34, 41, 50, 80,
20, 29, 36, 42, 50, 81]
21, 30, 37, 43, 51,
23, 31, 37, 43, 52,
23, 31, 38, 45, 52,
23, 31, 39, 47, 52,
nops(ageList) 75 Since this number is odd, the median can be obtained by executing the command median : ageList[floor(75/2)1] 37 If the data set contains an even number of elements, as in datatemp[1,2,3,4,5,6], the median is the arithmetic mean of the two terms in the middle, in this case 3 4 /2 7/2. datatemp:[1,2,3,4,5,6]: median : (datatemp[nops(datatemp)/2 ] datatemp[nops(datatemp)/21])/2 7/2 In MuPAD, we have a very useful procedure for obtaining the mode of the data set. For example, the mode for ageList can be calculated as follows:
222
Getting started with MuPAD
stats::modal(ageList) [33], 5 This result tells us that the modal value is 33 and that it occurs 5 times. If a data set is arranged in order of magnitude, the median divides the data set into two equal parts. By extending this idea, we can introduce values that divide the data set into four equal parts. These values, denoted as Q 1 , Q 2 , and Q 3 , are called the first, second and third quartiles, respectively. Observe that the second quartile Q 2 is equal to the median. Similarly, the values that divide the data set into 10 equal parts are called deciles, and are denoted by D 1 , D 2 , T , D 9 . Finally, we can talk about percentiles, P 1 , P 2 , T , P 99 , by dividing the data set into 100 equal parts. In MuPAD 3.1, we do not have a procedure to calculate quartiles, deciles and percentiles. However, we can use the procedure quantile developed for my statistics classes. The procedure requires three parameters—the data set, the base for the quantile calculation (4 for quartiles, 10 for deciles, or 100 for percentiles), and the number of the quantile (1, 2, 3 for quartiles, etc.). quartiles : quantile(ageList, 4, 1), quantile(ageList, 4, 2), quantile(ageList, 4, 3) 27, 37, 48 deciles : quantile(ageList, 10, i) $ i1..9 20, 47/2, 29, 33, 37, 81/2, 47, 50, 63 Check how the obtained quartiles and deciles fit into the ageList data set. A good visualization of the data spread is the so-called box and whisker plot, more commonly called the box plot. A box plot for a single set or multiple sets of data can be produced using the plot::Boxplot class. Although the simple statement for a box plot fulfills its role quite well, it is sometimes worthwhile to adjust it using additional parameters or the Virtual Camera. Below we show a box plot for two sets of data, ageList and ageList2. The final plot was adjusted in the Virtual Camera. Observe also that the isolated points on the right side show the outliers for each set of data, the numbers that are separated in some sense from
Chapter 6 ( Data visualization and elementary statistics
223
the rest of data. For more precise information about outliers, check a statistics textbook. In our example, they are the numbers 80 and 81 for the ageList and 72 for the second list. The vertical lines in each plot, starting from the left, represent the minimal value, Q 1 , the median Q 2 , Q 3 , and the maximal value of the set of data excluding outliers. B : plot::Boxplot(ageList, ageList2, DrawModeHorizontal ): plot(B, ViewingBoxXMin0) y
2
1
0
10
20
30
40
50
60
70
80
x
Note that the resulting box plot was modified with the Virtual Camera. Exercise 6.4 1. Calculate the arithmetic mean, mode, median and all three quartiles for the gradeList and gradeList2 data sets from exercise 6.3. Obtain the box plot for both sets of grades and use it to compare exam results. 2. The geometric mean of a set of positive numbers x 1 , x 2 , . . , x N can be expressed by the formula G N x 1 x 2 . . . x N . Calculate the geometric means for the gradeList and gradeList2 data sets. 3. The harmonic mean of a set of non-zero numbers x 1 , x 2 , . . , x N can be expressed by the formula N H N ! i1
1 xi
224
Getting started with MuPAD
Calculate the harmonic means for the gradeList and gradeList2 data sets. 4. The root mean square, also called quadratic mean, of a set of numbers x 1 , x 2 , . . , x N can be expressed by the formula N x 2i ! i1
N Calculate the root mean square for the gradeList and gradeList2 data sets. 5. Calculate Q1, Q2, Q3, D 1 , D 2 , D 5 , D 8 , and D 9 for the gradeList data set.
6.5 5 Standard deviation From calculating the arithmetic mean of data it is only a small step to calculating the standard deviation and other measures of data dispersion. Using techniques similar to those from the previous section, we can calculate the so-called mean deviation N 1 |x " x| N ! i1 i of a data set x 1 , x 2 , . . , x N , the standard deviation N x " x 2 ! i1 i
N or even the standard deviation for the data set x 1 , x 2 , . . , x N , with frequencies f 1 , f x , . . , f N : N f x " x 2 ! i1 i i
N Sometimes, instead of developing our own code for standard deviations, it is easier to use the right procedure from the stats library. Let us remind ourselves first about the ageList data set.
Chapter 6 ( Data visualization and elementary statistics ageList 23, 23, 31, 31, 38, 39, 45, 47, 52, 52,
: [3, 5, 7, 7, 23, 24, 25, 26, 31, 32, 33, 33, 39, 39, 39, 40, 47, 47, 48, 48, 59, 63, 63, 69,
225
9, 18, 19, 20, 20, 20, 21, 23, 27, 28, 29, 29, 29, 30, 31, 33, 33, 33, 34, 36, 37, 37, 40, 41, 41, 41, 42, 43, 43, 49, 50, 50, 50, 50, 51, 52, 71, 73, 75, 80, 81]
We have the mean deviation and standard deviation: float(stats::meandev(ageList)) 13.09333333 float(stats::stdev(ageList, Population)) 16.89733707 In MuPAD, we are able to use two different formulas to calculate standard deviations. The statement stats::stdev(ageList,Population) calculates the standard deviation if we are dealing with the whole population, and the statement stats::stdev(ageList) calculates the standard deviation for a sample taken from a larger population. We leave these considerations to the reader and move on to another topic. Exercise 6.5 1. Calculate the mean deviation and the standard deviation for the gradeList and gradeList2 data sets from the exercise 6.3. Which class has the smaller standard deviation and what does this mean in your opinion? 2. In MuPAD, we can use the procedure frandom() to obtain a random floating point number, e.g. frandom() $ i1..3 0. 2703567032, 0. 8142678572, 0. 1145977439 Use the frandom procedure to produce a data set with 10 random numbers and calculate the mean and standard deviation for this data set. Use the same procedure again to produce a data set with 1000000 random numbers. What will the standard deviation be this time?
226
Getting started with MuPAD
6.6 6 Correlation and regression Given two or more sets of data, we can investigate what dependencies exist between the data. For example, suppose we have data sets describing the average temperature, air pressure and rainfall for each month throughout a whole year. We can investigate how the rainfall depends on the temperature, how the rainfall depends on the air pressure, and so on. Let us look at a quick example. We will use for it real weather data from my favorite place, the town Lae in Papua New Guinea. The data was collected from the web site www.worldclimate.com. temperature : [27.4, 27.5, 27.3, 26.8, 26.2, 25.5, 24.9, 25.0, 25.5, 26.1, 26.8, 27.1]: rainfall : [274.8, 236.0, 316.8, 395.5, 389.4, 420.4, 507.1, 535.4, 436.5, 407.9, 319.7, 339.9]: pressure : [1007.0, 1006.9, 1007.4, 1008.5, 1009.7, 1010.8, 1011.1, 1011.3, 1010.9, 1010.2, 1008.8, 1007.5]: Each data set contains 12 numbers, one for each month. Suppose that we try to plot points with the coordinates x i , y i , where x i and y i belong to two different sets of data. We obtain a scatter plot showing how one data set is dependent on the other if such dependencies exist. In order to obtain the plot, we use the plot::Scatterplot class. A : plot::Scatterplot(temperature, rainfall): plot(A) y 500
450
400
350
300
250 25.0 25.2 25.4 25.6 25.8 26.0 26.2 26.4 26.6 26.8 27.0 27.2 27.4
x
Chapter 6 ( Data visualization and elementary statistics
227
A : plot::Scatterplot(pressure, temperature): plot(A) y
27.5
27.0
26.5
26.0
25.5
25.0 1007.0
1007.5
1008.0
1008.5
1009.0
1009.5
1010.0
1010.5
1011.0
x
A : plot::Scatterplot(pressure, rainfall): plot(A) y 500
450
400
350
300
250 1007.0
1007.5
1008.0
1008.5
1009.0
1009.5
1010.0
1010.5
1011.0
x
The line on each of these graphs is the linear regression line that can also be obtained using the stats::linReg procedure. For example, for the combination of temperature and rainfall, we obtain the equation, y 2735. 029216 " 89. 34182409 x
228
Getting started with MuPAD
stats::linReg(temperature, rainfall) [[2735.029216, -89.34182409], 9427.543371] Using another procedure from the stats library, we can calculate the correlation between two variables. For example, stats::correlation(temperature, rainfall) -0.9444266807 stats::correlation(pressure, temperature) -0.977174577 stats::correlation(pressure,rainfall) 0.9147798058 Each of the three obtained results shows a fairly good correlation between our data —each result is close to 1 (positive correlation) or "1 (negative correlation). It looks as though we have reached the point where statistics is becoming interesting and practical. Let us leave it at that for now. You can start your own independent explorations of statistics with MuPAD, or proceed to the next chapter. Exercise 6.6 Use the web site www.worldclimate.com to collect the rainfall, temperature and air pressure data for a few different places in the world such as Paris, London, or Jakarta. Copy the data from the web into MuPAD and declare them as lists. 1. Calculate the standard deviation for each set of data. 2. Calculate the correlation for selected pairs of data sets 3. Obtain a scatter plot for selected pairs of data sets. 4. Find another set of data where you expect a correlation between variables to exist. For example, you can use the height and weight of people, or the grades of students in school versus the number of children in their family.
A brief introduction to programming I strongly believe that a basic knowledge of programming is a must for mathematicians and mathematics teachers. Why? In mathematics, as well as in science, and many other disciplines, we deal with algorithms. Examples of such algorithms in mathematics are the Euclidean algorithm for finding the greatest common divisor of two integers, the Eratosthenes sieve, the Gaussian iteration method for solving linear equations, and many others. These algorithms are almost like programs. When we apply them, it is like executing a computer program. The only difference is that, when we apply an algorithm, we do all the calculations by hand or using a calculator, while with a computer program, it is the computer that does the calculations, and we enjoy getting a ready-made result. This way we can speed up our work. For example, an engineer instead of spending a few days solving several systems of equations by hand, will get the solutions in a matter of minutes or hours. This is one of the gains from the knowledge of programming. Another is that programming may help us to understand the complexity of some algorithms and mathematical problems described by these algorithms. Finally, programming is fun, like solving mathematical puzzles or crosswords, and many people enjoy programming as a sophisticated form of entertainment.
230
Getting started with MuPAD
In MuPAD we have a powerful programming language, similar to the well-known languages Turbo Pascal or, later, Delphi. Many teachers use dialects of Pascal for teaching high school computer science. In fact, MuPAD contains three programming languages. But this is completely different story. There is one important advantage to learning programming in MuPAD over many other programing languages. In MuPAD we have very easy access to graphics. Therefore, we do not need to stick to boring numerical examples. We can learn programming while creating some interesting graphical objects.
7.1 1 Variables again We have already spoken about variables and we have been using them throughout the book. Let me remind you quickly of some basic information about variables, from a programmer’s point of view. In a computer program, variables are like boxes where we store information. The information can be as simple as an integer, or as complex as a table with thousands of entries, with each entry being another complex object. Each variable occupies part of the computer’s memory. The space allocated for a variable usually depends on the variable type. Therefore, the more variables a computer program uses, and the more complex the objects stored in these variables, the more computer memory is used. This simply means that a computer program with too many variables containing complex information slows down the computer’s work quite significantly. A variable can store only one thing at a time. We cannot store two different things in the same variable at the same time. If we store something new in a variable then the old thing will disappear from it. This can sometimes be more complex than it appears. Let us consider what happens with the variables in the following example, where the assignment operator : is used to store data in a variable. A B A C C
: : : : :
1.23: A: A*100: 200: C1:
Now we check the contents of A, B and C.
Chapter 7 ( A brief introduction to programming
231
A, B, C 123, 1.23, 201 We can see that in the first statement, we created a variable A and assigned to it the value 1. 23. Then we copied the value from A to B. This did not change the value stored in A. In the third statement we took the current value of A, multiplied it by 100, and again assigned it to A. Finally, the second last statement created a new variable C with 100 assigned to it, and in the last statement we took the current value of C and increased it by 1. These few lines of code can be considered as a MuPAD program. In fact, most of the MuPAD code in the previous chapters of this book can be considered as programs. However, the real programming starts when we use special programming constructions. We will talk about them in the later sections of this chapter. We can declare variables one by one, as we did a moment ago. On some not so rare occasions, we need to declare a large number of variables. Let us look how, for example, we can declare 10000 variables at once. We will create the variables x1, x2, x3, ..., x10000 and we will assign some values to them. (x.i : i^2) $ i1..10000: Now, we can check if what we did is right. Let us ask MuPAD to print the contents of the variables x1, x23, x567, x9999. x1, x23, x567, x9999 1, 529, 321489, 99980001 (x234 x456)/x76 65673 1444
This way of declaring variables opens up some interesting opportunities. For instance, we can create 10 functions and plot them with two very simple statements. With the same number of statements we can produce and plot 10, 000 functions. Only, who needs this? Functions : (a.i : x^i) $ i1..10: plotfunc2d(Functions, x0..1)
232
Getting started with MuPAD
y
1
0.5
0 0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
x x^2 x^3 x^4 x^5 x^6 x^7 x^8 x^9 x^10
Let us end our discussion of variables by introducing indexed variables. We can create indexed variables a 1 , a 2 , ..., a n by using the index operator [ ]. For instance, for us, a[1] will mean a 1 . Let us consider a simple example, where we create 10 indexed variables a n , and assign them the values n . n1
(a[n] : n/(n1)) $ n1..10 1 2
,
2 3
,
3 4
,
4 5
,
5 6
,
6 7
,
7 8
,
8 9
,
9 10
,
10 11
We can check what we did and, for example, what happens if we try to access an indexed variable that we did not create. a[4], a[7], a[21] 4 5
,
7 8
, a 21
While declaring a set of indexed variables, MuPAD organizes them into a table. Therefore, we can also access the whole table by its name. For example, b[1] : 123: b[2] : 234: b
Chapter 7 ( A brief introduction to programming
233
1 123 2 234 Observe that we can also store functional expressions and functions in indexed variables. a[1] : x^2: a[2] : (x - x^2): a
1 x2 2 x v x2 We can use these variables as mathematical expressions or functions respectively. subs(a[1], x2) 4 a[2](2) 4 Exercise 7.1 Each of the exercises below may leave a large number of unwanted variables in your MuPAD notebook. Therefore, before starting a new problem, execute the reset() statement. 1. Create two variables A and B and assign to them the values 123 and 456 respectively. Write a short program to swap the contents between these variables. 2. Write one single declaration of variables x1, x2, x3, x4, and x5, which assigns to them the values 2 2 , 3 3 , 4 4 , 5 5 and 6 6 , respectively. Calculate the arithmetic mean of these numbers. 3. Write a single declaration that creates a sequence of functions sin nx, where n 1. . 10. Plot all these functions in the same coordinate system. Do this exercise again, this time using indexed variables. 4. Write a single declaration that creates a sequence of functions yn sin 1x sin 2x . . sin nx, where n 1. . 10. Plot all these functions in the same coordinate system.
234
Getting started with MuPAD
7.2 2 Procedures In previous chapters of this book, we declared a number of functions. Some of them were quite sophisticated. However, we may still come up with an idea of a function that is very difficult to declare as a MuPAD function. In fact, any mathematical activity can be treated as a function—we begin with some mathematical facts, perform calculations for a few hours, and then we obtain a result. How can we write such things as MuPAD functions? Here, the concept of a procedure is very useful. In practice, a procedure works exactly like a function, but its declaration is more flexible and allows to use as much code as we need. Let us start with a simple example to illustrate the similarities and differences between MuPAD functions and procedures. We are going to declare the arithmetic mean of two numbers as a function and then as a procedure. In order to distinguish between the two arithmetic means defined, I will use the lowercase word mean for the function and the uppercase Mean for the procedure. We will start by declaring the mean as a function. mean : (x,y) - (xy)/2 Now we declare the mean as a procedure: Mean : proc(x,y) local u; begin u : (xy)/2; return(u) end_proc: Here mean and Mean are the names of the function and the procedure respectively. In the first line of the procedure declaration, we listed the variables, the so-called input parameters of the procedure (here x and y). Then, between the two keywords begin and end_proc, we entered everything that we want to calculate. The included commands form the so-called body of the procedure. The final return statement produces the output of the result or results. We actually do not need to use the return statement. The output from the procedure is the last result produced. However, sometimes it is important to have full control over our programs. Observe that in the procedure declaration we also declare so-called local variables. These are variables that are used internally in a procedure, and their values do not affect any variables declared outside of
Chapter 7 ( A brief introduction to programming
235
a procedure, even if they have exactly the same name. Let us see how we can use the Mean procedure. Mean(123,456), mean(123,456)
579 , 579 2 2 The above example shows that both mean and Mean produce exactly the same result. In fact, procedures should be considered as an extension of the concept of a function. Before we move on to another topic, let us concentrate a moment on the final return(u) statement. Any procedure may have a few return statements. However, when one of them is executed, the procedure terminates. This means that from a procedure we cannot obtain two outputs from two different returns at the same time. A procedure like the one below will output only a and will never output b. test : proc(a,b) begin return(a); return(b) end_proc: Therefore, if we want a procedure to produce multiple results, we must organize them in a kind of structure, and output the whole structure. Let us consider a procedure that calculates the terms of the sequence a k "1 k k and outputs all terms for k n. . m. k1
sequence : proc(n,m) local temp; begin temp : k/(k1)*(-1)^k $ kn..m; return(temp) end_proc: Let us check if we get what we want. sequence(9,15)
" 109 ,
10 11
, " 11 , 12
12 13
, " 13 , 14
14 15
, " 15 16
sequence(1500,1505) 1500 1501
, " 1501 , 1502
1502 1503
, " 1503 , 1504
1504 1505
, " 1505 1506
236
Getting started with MuPAD
The produced result is a sequence of numbers, as expected. However, we could also use other structures such as lists, sets, matrices or tables. Before we proceed to other topics, it is helpful to show how we can write a simple program, using one or two procedures. Suppose that we would like to develop a simple pattern using squares, make a few copies of it, translate them to new places, and finally plot the entire pattern. For the purpose of this example, we will use the turtle class that we had investigated while talking about MuPAD graphics. Here is a complete program, with comments. // Program to draw pattern of squares, // June 2nd, 2005 // —————————————————————————————————————————– // procedure to draw a square with given side // —————————————————————————————————————————– square : proc(side) local T; begin T:plot::Turtle(); T::forward(side); T::right(PI/2); T::forward(side); T::right(PI/2); T::forward(side); T::right(PI/2); T::forward(side); T::right(PI/2); return(T) end_proc: // —————————————————————————————————————————– // procedure to make 4 copies of a pattern // note: pattern must be a list or set of // graphical objects // —————————————————————————————————————————– fourCopies : proc(pattern, distance) begin s1 : op(pattern): s2 : plot::Translate2d([distance,0], s1): s3 : plot::Translate2d([0,distance], s1): s4 : plot::Translate2d([distance,distance], s1): return(s1,s2,s3,s4) end_proc: // here we start using our procedures
Chapter 7 ( A brief introduction to programming
237
// develop a list of squares squares : [(square(i) $ i1..10)]: // develop the final pattern myPattern : fourCopies(squares, 11): // finally plot the whole pattern plot(myPattern)
You can try to experiment with the program. For example, change the translations into rotations, use a different distance for the translations, and so on. Exercise 7.2 1. Write a procedure that produces the geometric mean of two numbers. 2. Write a procedure that produces the arithmetic mean, the geometric mean, and the harmonic mean of two numbers, and returns all three of them at once. 3. Write a procedure that produces an equilateral triangle (using the plot::Turtle class), given the length of a side, and use it in a program that produces 10 triangles with sides of lengths from 1 to 10. 4. Write a program to plot ten concentric hexagons with ‘radius’ r 1. . 10.
238
Getting started with MuPAD
7.3 3 Getting organized After having used MuPAD for some time, many of us will have created hundreds of procedures performing various tasks. It will then be convenient to have all these procedures in one place, where we can easily save them and use them later. For this reason, we should create a single dedicated folder for all of our MuPAD work. A very convenient place for this folder is My Documents if we use the Windows platform, or any other appropriate place for other operating systems. Then we can configure MuPAD so it uses this folder for our works as its default folder. To begin, let us create a new folder in c:\My Documents (or in D:\My Documents) and call it MuPAD (or mupad). This will be the place for our procedures and other MuPAD files. Now we have to tell MuPAD where to look for its files. In order to do this, let us enter the following commands into a new, empty MuPAD notebook. READPATH : "d:\\My Documents\\MuPAD": WRITEPATH : "d:\\My Documents\\MuPAD": // here you can put more statements if // you need them print("My configuration of MuPAD.") The first two lines point MuPAD to the place that we have created for our files. Note that depending on the version of Windows, you may have My Documents in drive C: or D: or some other other drive. Note also the double back slash in the READPATH and WRITEPATH lines. This is not an error. It must be like this. The last print statement can be a bit annoying for longer terms. We can remove it later when we are sure that everything works fine. Export this notebook as the MuPAD source file userinit.mu to the created folder. This will be our configuration file. In fact we can create a number of such files and call them userinit.mu, or userpref.mu or graphcofig.mu, and so on. Each of these files may contain a configuration that is convenient for a specific purpose. Finally, we must tell MuPAD where to find the configuration file. In the MuPAD menu View, find Options... and select the Kernel tab. Here click the button with three dots to the right of the User-defined startup file and
Chapter 7 ( A brief introduction to programming
239
browse to the userinit.mu file we have created just a moment ago. Figure 7.1 shows what this looks like on my computer. That is it. Now, if we open a new notebook, MuPAD first reads the configuration file, and we see, on the screen, the output from the last print statement.
Fig. 7.1 Setting up user configuration file Technical comment Different versions of MuPAD have had different policies for user startup configuration files. In some of earlier versions we could only have one configuration file, and we only had to specify the access path to it. In later versions, ver. 3.1 and above, we can use multiple configuration files.
7.4 4 Creating user libraries Now, when MuPAD knows where to save and read procedures, let us create a simple library of procedures, save it and learn how to use it. To begin, let us create a new notebook and type in the following code. MyPI : 3.14159: toDeg : proc(x) begin return(float(x*180/PI)) end:
240
Getting started with MuPAD
toRad : proc(x) begin return(PI*x/180) end: information : proc() begin print("Trigonometric procedures: toDeg,toRad") end: As you can see, we declared the number = with accuracy to 5 decimal places, created two simple procedures for converting radians to degrees and degrees to radians, and wrote a procedure for printing brief information about the contents of the library. Before we save our procedures, we can try them out to check if they do what we really want. toDeg(2*PI/4) 90.0 toRad(361) 361 180
=
information() "Trigonometric procedures: toDeg, toRad" The last step is to export the content of the notebook to a *.mu file. write(Text,"tryg.mu",MyPI,toRad,toDeg,information) After executing the last statement, MuPAD creates a new source file tryg.mu. This file now contains all the procedures and constants that we specified in the write statement. The tryg.mu file can be opened in MuPAD, corrected, expanded and saved again. Let us load the tryg.mu file. read("tryg.mu") Now we can start using the tryg.mu library. information() "Trigonometric procedures: toDeg, toRad"
Chapter 7 ( A brief introduction to programming
241
toDeg(PI/3) 60.0 toRad(120)
2= 3 In exactly the same way we can create a number of libraries with our own procedures and use them in our work. If we would like to load them automatically every time MuPAD starts, we can add appropriate read statements into the userinit.mu file. It is important to mention that the libraries we created are simplified versions of MuPAD libraries. With some additional efforts, we can make them work like genuine MuPAD libraries. Exercise 7.4 1. Develop a library of procedures for calculating the area of a triangle for the given data (one side and height, two sides and angle between them, three sides). 2. Develop a library of procedures for calculating the volume of a sphere, cone, and cylinder. 3. Develop a library of procedures for calculating the surface area of the following solids: sphere, cone, and cylinder. 4. Develop a library of procedures using the plot::Turtle class to draw a triangle, a square, and some other figures. The number of sides of a figure should be used as input parameter for each procedure.
7.5 5 Control structures In mathematics, we often have situations where we choose what to do next depending on a logical condition. It also happens that some operations are performed repeatedly until a logical condition is fulfilled. The MuPAD programming language allows us to program such situations. However, before we start writing our programs, let us concentrate a while on logical conditions in MuPAD.
242
Getting started with MuPAD
7.5 5.1 1 Logical conditions A logical condition in MuPAD can be any expression that may be true or false. Here are a few examples of such conditions: 1 2, 10 5, sin(x) 1, x^2 y^2 1
1 2, 10 u 5, sinx 1, x 2 y 2 1 In each case, we can ask if these conditions are true or false. is(1 2), is(10 5) FALSE, TRUE MuPAD produces results that are known as logical or Boolean values. The values TRUE and FALSE form a kind of algebra with the logical connectors or, and, not as operations. not(TRUE and FALSE) and not(TRUE or FALSE) FALSE FALSE or TRUE TRUE We can easily check that MuPAD knows the whole propositional calculus from a Logic and Set Theory course. Let us return to our logical conditions. is(sin(x) 1) UNKNOWN is(x^2 y^2 1) UNKNOWN Here is something new. We got the result UNKNOWN since the expressions sinx 1, x 2 y 2 1 are not really logical propositions. They are so-called predicates and their value depends on the parameter that we used. For example, whether the expression x 2 y 2 1 is true or false depends on the values we substitute for x and y. is( subs(x^2y^21, x1/3, y1/2) ) FALSE
Chapter 7 ( A brief introduction to programming
243
is( subs(x^2y^21, x1, y1) ) TRUE The most interesting thing is that MuPAD uses a two-valued logic that can easily be extended to a three-valued logic by considering UNKNOWN as a third logical value. In that case, we get FALSE and UNKNOWN FALSE TRUE or UNKNOWN TRUE TRUE and UNKNOWN UNKNOWN not(TRUE and UNKNOWN) and not(TRUE or UNKNOWN) FALSE Exercise 7.5.1 1. Write a few logical conditions and check if they are true or false. 2. Write a few predicates and check for which values MuPAD considers them as true and for which as false.
7.5.2 Making decisions To begin with, let us suppose that we have the well-known function fx sinx x . This function, declared in MuPAD, performs quite well until we try to calculate f0 . For example, we have f : x - sin(x)/x
x¯
sinx x
f(PI), f(12.45), f(-34.98) 0, -0.009325955128, -0.01172168086 f(0) Error: Division by zero;
244
Getting started with MuPAD
during evaluation of ’f’ A logical way of fixing the declaration of this function is to use a conditional expression that tells MuPAD to calculate the value of the function for x p 0, and outputs some other value for x 0. Here is a possible solution. f : x - if x0 then 0 else sin(x)/x end_if: This declaration seems very complicated, but it works. f(PI), f(12.45), f(-34.98), f(0) 0, -0.009325955128, -0.01172168086, 0 Declaring functions with conditional expressions can be a bit complicated. However, we know that functions are procedures. So we can use a procedure that replaces our function. F : proc(x) local result; begin if x0 then result:0 else result:sin(x)/x end_if; return(result) end_proc: Our procedure works in exactly the same way as our function. But its declaration is much clearer. F(PI), F(12.45), F(-34.98), F(0) 0, -0.009325955128, -0.01172168086, 0 Technical comment The programming construction described here is known as an if-then-else control structure, or a conditional structure or an if structure for short. The if structure can be used in a simplified form such as if..then..end_if. Technical comment While writing programs in MuPAD and other programming languages, it is convenient to use indents. This is the best way to highlight the structure of the program. For instance, the statement if x0 then result:0 else result:sin(x)/x end_if contains two further statements, result:0 and
Chapter 7 ( A brief introduction to programming
245
result:sin(x)/x. By using indents we are able to show the dependency between successive statements. In this book, we usually use three spaces for indents. Many of us may have never noticed the fact that the solutions of many school problems use the if control structure. A typical example is the algorithm that high school students use to solve a quadratic equation. This algorithm actually gets quite complex if we write it formally as a MuPAD program. I suggest that you analyze this program and identify the major steps involved in solving a quadratic equation. Observe also that the program presented below is a simplified version of the algorithm. Some cases are still missing, such as the solutions that are complex numbers. a : 1: b : 4: c : 2: if a0 then delta : b^2 - 4*a*c; if delta 0 then x1 : (-b sqrt(delta))/(2*a); x2 : (-b - sqrt(delta))/(2*a); x1, x2 else print("No real results") end_if else if b0 then x1 : -c/b else print("No results") end_if end_if
2 " 2, " 2 " 2 The given program can be converted into a procedure. We can of course make many other improvements, but this depends on our needs and programming skills. Here is our program again, but this time as a procedure. Quadratic : proc(a,b,c) local delta, x1, x2; begin if a0 then delta : b^2-4*a*c;
246
Getting started with MuPAD
if delta 0 then x1 : (-b sqrt(delta))/(2*a); x2 : (-b - sqrt(delta))/(2*a); return(x1, x2) else print("No real results") end_if else if b0 then x1 : -c/b; return(x1) else print("No results") end_if end_if end_proc: Technical comment In declarations of procedures and control structures, the ending keywords end_proc, end_if, ... can be simplified to just end. Moreover, in nested if-then-else statements, the consecutive keywords else and if can be replaced by the keyword elif. In this way, we can simplify our code. Exercise 7.5.2 1. Develop a procedure min(x,y,z) that takes as input three real numbers and outputs the smallest one. 2. Develop a procedure ord(x,y,z) that takes three real numbers and outputs them in ascending order. 3. Develop a procedure that produces the value of
1 1"x 2
for a given x if
such a value exists or infinity if the value of the fraction does not exist. 4. Write a procedure that returns the value of the expression x 2 " 1 4 " x 2 for a given x if such a value exists, and zero otherwise. 5. Write a procedure, using plot::Turtle, that outputs a triangle if the input is 3, a square if the input is 4 and a hexagon if the input is 6. For other values of the input, the procedure should print a message asking the user to use 3, 4, or 6.
Chapter 7 ( A brief introduction to programming
247
7.5.3 Iterations Other types of control structures are the for-do, repeat-until and the while-do structures, sometimes referred to as iteration structures or, more frequently, as loops. We use them to program frequently repeating tasks. For example, adding the terms of a series to produce its partial sums. The for-do structure we use in problems where the number of repetitions is known ahead of time. If the termination of the repeated task depends on a logical condition, then we use the control structures repeat-until or while-do instead. We will start exploring the iteration concept with a very simple example. Let us try to use the for-do control structure to calculate the n-th partial 10 "1 k k . sum of the series ! k1 k1
We begin the code by declaring the initial value of the psum variable. Then we use the iteration structure, specifying how many steps of calculations should be carried out, in this case 10 steps, and then we write what should be done at each step. The description of the steps is enclosed in a kind of for ... end_for bracket, with two consecutive statements inside the bracket separated by a semicolon. The rest is quite obvious—in each step, we calculate the value of the k-th term and then add its value to the growing partial sum. psum : 0: for k from 1 to 10 do term : k/(k1)*(-1)^k; psum : psum term; end_for
7303 27720 From this first example of an iteration we can see that the sequence operator that we used many times was already a simplified version of the for-do loop. By combining iterations with procedures and graphics we can produce very useful visualizations. Below we show how we can visualize the behavior of the partial sums of our series. In this example, we calculate the partial sums of the series, and then we create a list of points ¡k, partial sum for k¢. At the end, we plot all these points using the
248
Getting started with MuPAD
plot::Polygon2d class. psum : 0: points : []: for k from 0 to 50 do term : k/(k1)*(-1)^k; psum : psum term; points : points.[[k,psum]] end_for: graph : plot::Polygon2d(points): plot(graph) y 0.2 0.1 0 10 -0.1
20
30
40
50
x
-0.2 -0.3 -0.4 -0.5 -0.6
Such a program can be easily turned into a procedure and added to our library. Below, we show how this can be done. SumPlot : proc(n) local psum, points, k, term; begin psum : 0: points : []: for k from 0 to n do term : k/(k1)*(-1)^k; psum : psum term; points : points.[[k,psum]] end_for: return(plot::Polygon2d(points, YGridVisibleTRUE)): end_proc: plot(SumPlot(100))
Chapter 7 ( A brief introduction to programming y
249
0.3 0.2 0.1 0 10 -0.1
20
30
40
50
60
70
80
90
100
x
-0.2 -0.3 -0.4 -0.5 -0.6 -0.7
Our procedure is very simple and does not have all the bells and whistles of other classes in the MuPAD plot library. However, you can try to enrich it with some useful features. For example, you can think about what changes would have to be made in the procedure so we can use it like here SumPlot(100, LineColorRGB::Red). Iterations and graphics were always used to develop some kind of mathematical art. With our knowledge of MuPAD graphics we can also try to develop something interesting. For instance, let us develop a sequence of circles with a growing radius and the centers located on the spiral of Archimedes. We can make our exercise even more artistic by adding random colors to our circles and animating the way they appear. This way, we get a very nice animation of the spiral of Archimedes. We start coding our example by declaring two important elements—the number of frames of the animation and an empty list of circles. Inside the for-do loop we declare a circle with the center on the Archimedes spiral and a reasonably small radius. In the second part of the circle declaration, we add separate parameters for the animation of each circle. We add here the dummy parameter a, which was not used anywhere in the circle declaration, then we add the time when the circle should appear, TimeBegink and whether it is visible before starting its animation VisibleBeforeBeginFALSE. Finally, the last statement plot(op(circles)) removes the square bracket from the list of circles and plots them.
250
Getting started with MuPAD
circles : [] : numberOfSteps : 40: p : 1.222: r : t-t^p: for k from 0 to numberOfSteps do t : k*PI/8; circle : plot::Circle2d( sqrt(2)*ln(t^21),[r(t)*cos(t),r(t)*sin(t)], FilledTRUE, FillPatternSolid, FillColor[frandom(), frandom(),frandom()], LineColorRGB::Black, // animation parameters ak..numberOfSteps, FramesnumberOfSteps - (k-1), TimeBegink, TimeEndnumberOfSteps, VisibleBeforeBeginFALSE ); circles : circles.[circle] end_for: plot(op(circles)) y 30
20
10
-30
-20
-10
10
20
30
x
-10
-20
I suggest you try entering the code of our example in a MuPAD notebook to check how the animation works. The trick with the animation parameter that we used here can be quite useful in many other situations. The two other types of loops, repeat-until and while-do, require a slightly different way of thinking. We do not use an iteration counter here.
Chapter 7 ( A brief introduction to programming
251
Instead, we use a logical condition that stops the iteration when it reaches a logical value—TRUE for repeat-until and FALSE for while-do. Let us see how we can calculate a sum of the terms of the sequence a n nn , that is larger than a given number, for example K 1/10000. As 2
before, we start the code by declaring the constant K, the formula of the sequence and some other necessary constants. This time, we use the while-do control structure. The iteration will be carried out as long as the condition termK is true, otherwise the iteration will stop and the last produced result of the variable psum will be printed. K : a : n : term psum
1/10000: n - n/2^n: 1: : a(n): : 0:
// here iterations start while term K do psum : psum term; n : n1; term : a(n) end_while: n-1, psum // here we print results
17,
262125 131072
Let us rework our example, but this time using the repeat-until control structure. The major change is that we move the logical condition to the end of the loop statement and reverse its logical functionality: instead of termK we use termK. K : a : n : term psum
1/10000: n - n/2^n: 1: : a(n): : 0:
// here iterations start repeat psum : psum term; n:n1; term : a(n) until termK end_repeat:
252
Getting started with MuPAD
n-1, psum // here we print results
17,
262125 131072
High school and university textbooks contain thousands of examples where iterations might be useful. Below is one of them. The Eratosthenes sieve is a very simple algorithm used to select a set of prime numbers in the given range 2. . K, where K is a positive integer. The algorithm selects the smallest prime number in the set of integers from 2 through K, removes from the set all of its repetitions, then selects the next prime number, removes its repetitions, and so on. You will have no trouble understanding the program below. The only thing that may need an explanation is the statement card(NaturalNumbers), used to calculate the number of elements in the set NaturalNumbers. R : 90: NaturalNumbers : { n $ n2..R}: // here we construct an empty set of prime numbers PrimeNumbers : {}: // here we start iterations while card(NaturalNumbers)0 do // select the smallest prime number element : NaturalNumbers[1]; // now we add the prime number to the set PrimeNumbers PrimeNumbers : PrimeNumbers union {element}; i:1; // now we remove multiplicities of element remove:element; repeat if remove in NaturalNumbers then NaturalNumbers:NaturalNumbers minus {remove} end_if; i:i1; remove:element*i; until removeR end_repeat end_while: PrimeNumbers // print results
£2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89¤
Chapter 7 ( A brief introduction to programming
253
Exercise 7.5.3 1. Write a procedure to calculate the sum of all integer numbers starting from 1 to a given number N. Use the for-do loop. 2. Write a procedure calculating
1 2 . . . N for a given number N. 1 2 . . . N
Use the for-do loop. 3. Write a procedure to calculate the product n n 1 n 2 . . . m for two given natural numbers n and m, where n m. Use the for-do loop. 4. The arithmetical mean of a sequence of numbers x 1 , x 2 , T , x N can be expressed by the formula x 1 x 2 T x N N Write a procedure to calculate the arithmetical mean of the sequence k x k 12 for k t N, where N is a given natural number. 5. For a given number A, we create the sequence 1 , 1 ,T 1, 1 , A A d A 2d A 3d Write a procedure to calculate the sum of N terms of the sequence for given values of A and d. 6. It is well known that if 0 a 1 then a n v 0. Write a procedure to produce the list of terms a n such that 0 b a n 1 for given b a. Use the repeat-until loop. 7. Write a procedure, using plot::Turtle, to draw a closed polygon with n sides and a given angle. In the procedure the turtle should be allowed to turn each time the given angle in the same direction. 8. Write procedures, using turtle graphics, to draw the patterns shown below.
254
Getting started with MuPAD
7.5.4 Sometimes iterations and conditions do not work We have already mentioned that in our programs, certain things may sometimes go wrong. We have encountered a few situations where something did not work as expected and were able to identify the problems. With loops and conditions, there is also something that may cause us some grief if we do not know what is going on. Let us start with a simple program. However, in order to be absolutely sure that MuPAD does not remember anything from previous exercises, let us reset the notebook. reset(): if (2.63-2.6250.005) then print ("OK") else print ("OOPS") end_if "OOPS" Indeed there is something wrong. It is quite obvious that 2. 63 " 2. 625 0. 005, however MuPAD thinks that this is not so. The reason lies in decimal arithmetics. As long as MuPAD uses exact numbers or symbolic calculations, we can expect that all its results are correct. However, when performing calculations with floating point numbers, MuPAD has to convert them to binary numbers first, because internally computers use binary numbers. Here is the problem. Not every floating point number can be converted to a binary number with a finite number of digits. Therefore, in order to perform further calculations, MuPAD sometimes has to truncate the obtained binary number. This introduces an error that makes 1 and 1. 0 completely different numbers. Let us do more experiments. Let us calculate the sum 1 1/10 11 . We will check first what MuPAD produces without floating point numbers. 1 10^(-11) 100000000001 100000000000
As we see, there are no surprises. Now, let us try the same using floating point numbers.
Chapter 7 ( A brief introduction to programming
255
a : 1.0 10^(-11)
1. 0 The result is not accurate, but this can be a fault of using too small value for DIGITS. Let us increase its value. DIGITS : 15: a 1.00000000001 Now, the result looks perfect. But it this really so? Let us check what happens for DIGITS50 or more. DIGITS : 50: a 1.0000000000099999999600419720025001879548653960228 Here we finally see that the real result is quite different from what we expected. The conversion from decimal to binary form described here reminds us of another well-known example from school mathematics. We know that the fraction 1 cannot be converted to a floating point number 3
without introducing an error. The conversion of 1 to a floating point 3
number produces a number with infinitely many digits, 0. 333333333333333333. . . Therefore, by cutting it to 0. 33333 or even to 0. 33333333333333333333, we introduce an error. Exactly the same happens when converting 1/10 11 to a binary number. The error mentioned here may have a serious impact on conditions and iterations. Here is another example where we face the same problem. i : 0.1: repeat i : i0.1: if i2 then print(i) end_if; if i5/2 then break end_if; until i2.0 end_repeat 2.1 2.2 2.3 2.4 2.5 2.6
256
Getting started with MuPAD
We can summarize this discussion by saying that in numerical calculations, it is safer to use exact numbers. However, if we have to use floating point numbers, we should use conditions with inequalities. For instance, the above example would work as expected if we used i2.0 instead of i2.0.
7.6 6 Recursion The wonderful example of the Fibonacci sequence, repeated over and over again in the mathematical literature, shows how important and effective recursion can be in some situations. Recursive procedures are build on the principle of mathematical induction. We have to know the starting element a 0 of a sequence, then we must be sure that if we know the n-th term a n of the sequence, we can calculate a n1 , the next term. These two rules are enough to ensure that we are can calculate all the terms of the sequence. Let us see how this works in the case of the factorial function n!. We know that 1! 1 and n 1 ! n 1 n!. This is enough to calculate the factorial of any natural number: 4! 4 3! 4 3 2! 12 2 1! 24 1 24 The factorial example can be used to write a recursive procedure in MuPAD. factorial : proc(n) begin if n0 or n1 then return(1) else return(n*factorial(n-1)) end_if end_proc: factorial(23) 25852016738884976640000
Chapter 7 ( A brief introduction to programming
257
This nice piece of code is a perfect explanation of what a recursive procedure is and how it works. I suggest you calculate by hand factorial(7) and see what happens when using a recursive procedure. In our example, a basic improvement is needed. Observe that we get an error message when trying to calculate factorial(-10). We know that the factorial of a negative number or even then factorial of a positive non-integer number do not exist. A simple addition to our code incorporates this information. factorial : proc(n:Type::PosInt) begin if n0 or n1 then return(1) else return(n*factorial(n-1)) end_if end_proc: Recursive procedures can prove to be very useful for various types of mathematical art. However, thinking recursively needs a bit of practice. Let us analyze the enclosed picture (fig. 7.2). Producing this fractal staircase with iterations is possible, but it requires quite a lot numbers crunching to produce the coordinates of each square. However, we can develop this fractal using recursion. We can start with the point 0, 0 and draw the first square with the left corner in 0, 0 —this will be level 0 of the recursion. Now, suppose that we have a square. By dividing its size by 2, and attaching to it two adjacent squares, one to the right and one up, with size size/2 we get the next step of recursion. Therefore, the rules are simple: 1. if step 0 then draw a square with a given size in a given point. 2. if step 0 then draw a square with given size size/2 in a given point, change step to step " 1 and calculate two points, right and up, for the next step. 3. repeat rules 1 or 2, depending on the value of steps.
258
Getting started with MuPAD
y
1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0.0 0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
x
Fig. 7.2 Fractal staircase, 6 steps The program to plot this fractal is a direct translation of our rules into MuPAD code. Note that we first created the square A with sides 1 1 and with its left corner at the point 0, 0 . Then we used multiple copies of this square, scaled to the appropriate dimension, and translated them to the appropriate spot. We used the variable steps as a counter for the number of steps in the recursion. This way, we are sure our program will terminate as required.. You can try this program to produce fractal staircases for 1, 2, 3, .., 8 steps. For larger values of the variable steps, the calculations may take a long time. Why? A:plot::Rectangle(0..1,0..1, FilledTRUE, FillPatternSolid ): squares : []: drawIn : proc(x,y,size) local B; begin B : plot::modify(A, FillColor[frandom(),frandom(), frandom()] ): B : plot::Scale2d([size,size],B): B : plot::Translate2d([x,y], B): end_proc:
Chapter 7 ( A brief introduction to programming
259
iterate : proc(x,y,steps, size) begin if steps0 then squares : squares.[drawIn(x,y,size)] else squares : squares.[drawIn(x,y,size/2)]: iterate(xsize/2,y, steps-1,size/2): iterate(x,ysize/2, steps-1,size/2): end_if end_proc: iterate(0,0,5,1): plot(op(squares),ScalingConstrained) For a large number of steps, recursive procedures can be very slow and use a lot of memory. The reason is simple. In our example for steps0, we create a single square, for steps1 we create 1 2 squares, for steps2 we create 1 1 2 2 2 7 squares and the procedure iterate is executed 7 times, for steps4 we create 1 1 2 2 2 4 2 15 and execute the procedure 15 times, and so on. How many squares do we calculate for steps15? Technical comment For some recursive procedures, where the calculations of a given term a n use a n"1 , a n"2 , and so on. We can speed up the calculations using the remember option like in the enclosed below example. factorial : proc(n:Type::PosInt) option remember; begin if n0 or n1 then return(1) else return(n*factorial(n-1)) end_if end_proc: Writing recursive procedures can be a nightmare for a beginning programmer. Therefore, I suggest to start from simple examples and after some time move to more complex graphical examples like those in figure 7.3.
260
Getting started with MuPAD
y 3
2
1
-2
-1
1
2
3
4
x
-1
-2
-3
Fig. 7.3 Two fractals obtained using recursive procedures This was the last example in the first edition of this book. I hope that after reading this text, you will be able to use MuPAD to solve many mathematical problems and, in particular, to visualize them. More information about using MuPAD and more examples of MuPAD programs are published on the web site for my books at http://majewski.mupad.com Exercises 7.6 1. Power a n , where n is a natural number can be defined by a n 1 if n 0 and a n a a n"1 for n 0. Write a recursive procedure to calculate a n , for any natural number n. 2. A partial sum of the terms of a sequence a n can be expressed by the formula sa n 0 if n 0 and sa n a n sa n"1 for n 0. Write a recursive procedure to calculate the partial sums of the sequence 1 1, 12 , 14 , 18 , 16 ,... 3. Modify the staircase fractal program to produce a 3D staircase. This time, the building components are rectangular blocks. 4. Write a program using a recursive procedure to plot a triangle fractal constructed out of circles (fig. 7.3 right). Hint: this problem is very similar to the fractal staircase, you need to plot a circle and calculate the radius and the centers for three next circles.
Index % … 31 : … 19 :: … 42 ; … 19 ? … 24 _and … 167 anames … 25
animation … 89 Annotation … 39 assume … 166 assuming … 169 assumptions … 166 Canvas … 37 CATALAN … 4 ceil … 96 class … 211 class boundaries … 211 class frequency … 215 collect … 11 color function … 50 complex numbers … 170 concatenation operator … 21 Constrained … 48 contour curves … 142 CoordinateSystem3d … 37 correlation … 226 CSV format … 199 cumulative frequency plot … 217 Current View panel … 38 curve-sketching … 114 cylindrical coordinates … 60 data dispersion … 224 data visualization … 195 deciles … 222 definite integral … 13 Definition … 39 delete … 30 density plot … 142 derivative … 110 detools … 134 Dichromatic … 39 diff … 110 differential equation … 132
differentiation … 12 DIGITS … 4 div … 6 Dom::Quaternion … 174 domain … 165 dot plot … 210 double dot plot … 216 E…4 end_if … 246 end_proc … 246 Eratosthenes sieve … 252 erf … 128 EULER … 4 exp … 6 factor … 178 factorial … 256 FALSE … 29, 242 Fibonacci sequence … 256 FillColor … 39 FillColorFunction … 51 FillColorType … 39 float … 7 floor … 96 for-do … 247 fractals … 260 frandom … 225 frequency density … 215 frequency distribution … 209 function declaration 14 Gauss function … 124 gradient vector field … 152 graphical object … 42 history … 31 if-then-else … 244 import::readdata … 205 indefinite integral … 13 info … 24, 26 infinity … 106 integration … 12 intersect … 21 ithprime … 97 Jacobian formula … 158 Koch snowflake … 83
262 last … 31 lcd … 178 lcm … 178
limits … 105 linalg … 179 linalg::det … 158 linalg::det … 193 linalg::Hilbert … 186 linalg::randomMatrix … 186
Lindenmayer systems … 83 LineWidth … 46 linsolve … 179 list … 21 L-systems … 83 L-systems symbols … 85 Maclaurin series … 120 matrix … 23 MaxDegree … 7 Mesh … 49 minus … 21 mod … 6 Monochrome … 39 multiple integrals … 154 nextprime … 96 nops … 219 numeric::int … 127 Object Browser … 37 OpenGL … 53 option remember … 259 parametric equation … 46 pareto diagram … 205 partfrac … 11 partial differentiation … 148 partial fractions … 11 particle … 89 Pascal matrices … 187 percentiles … 222 PI … 4 piecewise … 98 piecewise function … 98 plot … 43 plot library … 43 plot::Arrow2d … 173 plot::Bars2d … 202
Getting started with MuPAD plot::Bars3d … 207 plot::Box … 73 plot::Boxplot … 223 plot::Cone … 73 plot::Curve2d … 46 plot::Curve3d … 63 plot::Cylindrical … 61 plot::Density … 142 plot::Dodecahedron … 73 plot::Function2d … 44 plot::Function3d … 50 plot::Group2d … 67 plot::Hatch … 125 plot::Hexahedron … 73 plot::histogram2d … 215 plot::Icosahedron … 73 plot::Implicit2d … 49 plot::Implicit3d … 56 plot::Inequality … 137 plot::Line2d … 67 plot::Lsys … 77 plot::Matrixplot … 188 plot::Octahedron … 73 plot::Piechart2d … 204 plot::Point2d … 67 plot::PointList2d … 67, 71 plot::Polar … 48 plot::Polygon2d … 71 plot::Rotate3d … 77 plot::Scale3d … 74 plot::Scatterplot … 226 plot::Sphere … 73 plot::Spherical … 58 plot::Surface … 54 plot::Sweep … 161 plot::Tetrahedron … 73 plot::Translate3d … 74 plot::Tube … 63 plot::Turtle … 77 plot::ZRotate … 163 plotfunc2d … 18
polar coordinates … 47 poly … 177 poly2list … 178
Index polynomials … 176 procedure … 234 Properties panel … 37 quartiles … 222 quaternion … 174 radsimp … 24 READPATH … 196, 238 recursion … 256 recursive procedure … 259 relative frequency … 215 repeat-until … 250 reset … 30 return … 235 RGB … 46 Riemann method … 128 Roman surface … 56 RootOf … 7 Scaling … 48 Scene2d … 41 Scene3D … 37, 41 sequence … 20 sequence operator … 22 set … 20 Si … 127, 128 sign … 105 Simplify … 10 simplify … 10 Simpson method … 128 slot operator … 42 solve … 6 sort … 221 spherical coordinates … 58 sqrt … 5 standard deviation … 224 stats::frequency … 195
263 stats::frequency … 213 stats::linReg … 227 stats::mean … 220 stats::meandev … 225 stats::modal … 222 stats::sample … 196 stdlib … 26
Steiner surface … 56 student … 27 student::plotRiemann … 129 student::plotSimpson … 130 student::plotTrapezoid … 130 student::simpson … 27
surface of revolution … 163 table … 198
Taylor polynomials … 120 Taylor series … 120 Toeplitz matrix … 187 trapezoid method … 128 TRUE … 29, 242 true class limits … 211 turtle commands … 79 turtle graphics … 78 Type::Imaginary … 168 types library … 168 UNDEFINED .. 100 union … 21 unit … 46 UNKNOWN … 29, 242 Vandermonde matrix … 187 VCam … 33 vector fields … 151 Virtual Camera … 33 while-do … 250 WRITEPATH … 196, 238