Today's users have a choice oI a wide variety oI devices: Personal computers Typically a computer Ior individual use can be expected to have the Iollowing Ieatures: 1. Processing capability oI a billion or more arithmetic or memory operations per second. SigniIicant amounts oI calculation are used in doing the graphics involved in processing digital media or supporting the artiIicial worlds presented in computer games. This same power can be used to do the simulation and exploration in many common kinds oI scientiIic and engineering situations. This course is about using that calculation power. 2. Standard selection and pointing devices, keyboard and mice. Some computers support "tablet" operation which allow use oI a pen writing on the display. The display area and input devices make it easy to enter inIormation via text or by pointing/selection. While the World Wide Web has made much processing possible with just "pointing and clicking", the complexity and mathematical sophistication oI the models used in current technical computing outstrip the capabilities oI current "point and click" technology. Some (computer programming) language-based interaction is necessary to handle things deItly. This requires a more knowledgeable user, but many people Iind that the extra power is worth the learning eIIort. 3. A screen capable oI displaying inIormation equivalent to one or more 8 1/2 x 11 inch pieces oI paper. This helps support the development oI documentation, or oI more complex visualizations. 4. Local storage capable oI storing a signiIicant Iraction oI the text oI the books in the Library oI Congress. OI course, it's easy Ior a personal media collection to Iill up this kind oI storage, but it should not be Iorgotten that the billions oI characters that this storage represents can store years or decades oI eIIorts oI computer programmers. 5. Connection to the internet, which makes it easier to communicate and share work with others, and to download new programming. From the viewpoint oI technical computing, that it's easy to import and run substantial amounts oI programming. High performance computers, also known as "supercomputers" 1.4 The spectrum oI devices Ior technical computing 3 While hand held devices and personal computers are used widely by the general public Ior non-technical purposes, there are a class oI computers that are used primarily Ior mathematically-based computing. Typically instead oI billions oI numerical operations per second ("gigaIlops" -- billions oI floating point operations), they employ multiple processors in parallel to do trillions oI operations ("teraIlops") or quadrillions ("petaIlops"). The hardware, personnel and energy costs oI such computers are signiIicant, so typically they are available through centers used through the Internet Irom many locations. The kinds oI technical problems such devices are used Ior would include: simulation oI complicated physical situations, such as Ior climate prediction, astrophysics, or engineering design (aircraIt, groundwater, large building, automobile). Using such large devices incur signiIicant expense, Irom hardware, soItware and support staII costs, as well as electrical power consumed. For example, the U.S. Department oI Energy has an IBM computer at its Los Alamos National Laboratory in New Mexico, USA capable oI 1 quadrillion ( ) numerical operations per second. It consumes 2345.50 kilowatts when it is running. (reIerence: http:// blog.enterpriseitplanet.com/green/blog/2008/06/green-petaIlop-ibms-roadrunner-wins-supercomputer-top-spot.html) The National Center Ior Computational Sciences (NCCS) at Oak Ridge National Laboratory in Tennessee, USA which has several large supercomputers, has a 2008 annual budget between $80 million and $100 million. (reIerence: http://news.cnet.com/8301-137723-9985500-52.html). A typical personal computer might be capable oI approximately 4 billion numerical operations per second, so the Blue Gene computer at Los Alamos provides roughly more computing power. Typically the programming is developed on personal computers, then moved to the larger devices. Usually the expensive supercomputer time is spent primarily on numerical computation, rather than on providing a nice-to-use interIace Ior users. However, the results oI a supercomputer may be shipped over the Internet to a personal computer so that a scientist or engineer may mull over the results in a more contemplative way without incurring additional supercomputer costs. Multiple computers may be linked together over the Internet to get all the pieces oI a particular elaborate computation done. This may have the supercomputers perIorming the massive numerical computations, while other smaller or personal computers linked in may be displaying the results to a distributed team oI investigators who are collectively digesting results and steering the on-going work. Hand held mobile devices Calculators are useIul Ior casual computation, where one wants to Iigure out the solution to a small problem once. It's easy to punch in a Iew numbers and operations and to read the answer on the display. As inexpensive and small mobile devices, these are typically more limited in: 1. memory (limits to computation size and to built-in Ieatures) 2. energy consumption (slower processor speed) 3. Iorm Iactor (keyboard and display too small Ior more than casual technical use) Typically calculators are not networked, making it harder to share results to transIer them elsewhere to continue the work. Table 1.2: A high-end calculator in 2009 The TI-Nspire with CAS is a recent generation calculator Irom Texas Instruments. It can do numerical and symbolic calculations, as well as graphing. According to ticalc.org (http://www.ticalc.org/basics/ calculators/ti-nspire-cas.html) it has 16Mb memory, 20Mb storage and has a 150MHz processor. This makes it have about 100 times less memory, 8000 times less storage, and makes it run twenty times slower than a low-end laptop with a dual core 1.5GHz processor, 2Gb memory, and 160Gb disk. Its screen is 240 x 320 pixels, giving it about twenty times less display area than a typical laptop. This is one oI the Iirst generation oI calculators with limited wireless networking available as an add-on.
See http://education.ti.com/educationportal/sites/US/productDetail/usnspirecas.html? subid1&topid350. 4 1 Introduction -- Technical computing in the 21st century
Smartphones, personal digital assistants (PDAs), media plavers, and tablets can have processing capabilities almost as powerIul as small personal computers. One advantage that these kinds oI devices hold over calculators, is that they are typically networked so that it's possible to use them as a Iront end to a more powerIul computer somewhere else in the Internet "cloud" oI computational resources. Mark Dean oI IBM, part oI the engineering team that developed the original PCs Ior that company in the '80s, has written that the wave oI popularity Ior personal computers has crested, "they're going the way oI the vacuum tube, typewriter, vinyl records, CRT and incandescent light bulbs." (http:// asmarterplanet.com/blog/2011/08/ibm-leads-the-way-in-the-post-pc-era.html). However the limitations oI the small display and keyboard with current mobile devices will continue to constrain the appeal oI such devices Ior extensive technical work Ior the near term. A high-end tablet in 2011 The iPad2 is a recent generation networked mobile device Irom Apple. According to http:// www.apple.com/ipad/specs/ and http://www.engadget.com/2011/03/09/ipad-2-review/, it can be conIigured with 512Mb memory, 64Gb storage, and a 1GHz dual core processor. Its screen is 1024 x 768 pixels. This makes it slightly less capable than a low-end laptop with a dual core 1.5GHz processor, 2Gb memory, and 160Gb disk.
Photo Irom http://4.mshcdn.com/wp-content/uploads/2010/01/ipad-3g.jpg Dedicated controllers Even some kinds oI toasters have microprocessors in them nowadays. "Smart homes" (see Ior example http://home.howstuIIworks.com/smart- home.htm and http://www.drexelsmarthouse.com/) may network appliances and home Ieatures such as HVAC and lighting control. While these devices are merely conIigured rather than programmed by end users, students oI technical computing should not Iorget that this is another place where programming is necessary. The economic reasons Ior switching to computer control oI devices appear to be the greater Ilexibility and variety oI control that can be developed at modest cost through programming Ior many kinds oI devices. The kind oI programming done Ior device control oIten has a mathematical basis. Although the processors in dedicated devices are typically a Iew orders oI magnitude slower than those oI personal computers or even smartphones, the programming languages used Ior them are oIten the same or similar to those used in personal computing. 1.5Maple, a system for technical computing In this course, you will learn how to do various kinds oI technical tasks using Maple. The Iirst version oI Maple was developed in the early 1980s at the University oI Waterloo in Ontario, Canada, but has since undergone many reIinements and extension. (In Fall 2011, we will be using Maple 15.) Maple's original emphasis was on algebraic computing, so it was used by those who needed Iormulas as results Ior their work. In the early '90s it was used extensively in calculus classes as a way oI supporting exploratory experimentation and more extensive experience with "applied" problems. More recently it has expanded its domain into the symbolic, numeric, and graphical calculations done more generally in scientiIic and engineering modeling and simulation. Today, Maple supports numerical computing and graphical visualization about as well as it does symbolic computing. It has its own programming language but also has ways oI doing calculations through the graphical user interIace (GUI) that is a kind oI augmented "point and click". The deIault way oI interacting with Maple also allows you to mix documentation and computing instructions and results. Thus it's particularly easy in Maple to produce documents that produce a well-documented solution -- a description oI the problem, the explanation Ior how to solve it, and the computations that produce the details oI the answer and evidence to justiIy its correctness. 1.6What about Systems X, Y, Z, ...7 There are a variety oI systems and programming languages used Ior technical computing nowadays. In the TIOBE Programming Community Index Ior August 2011, Java, C, C, PHP, C#, Objective C, Visual Basic, Python, Perl and JavaScript are, in that order, the ten most popular programming languages (see http://www.tiobe.com/index.php/content/paperinIo/tpci/index.html). In a large technical establishment such as 1.7 Why pick Maple as the Iirst system? 5 a university or research lab, one might Iind, in addition to the generally popular languages and Maple, systems such as Matlab, Mathematica, Octave, Macsyma, Sage, Axiom, REDUCE, Mupad, and Fortran. Maple and other "niche" languages are used despite the much greater popularity oI the "top 20" languages because they specialize in addressing tasks common in technical Iields. The vast array oI tasks computers can be used Ior, the multiplicity oI philosophies oI system design, and the rapid and unrelenting nature oI progress in computing means that there is no "best system" Ior any situation. Each system has its technical strengths. There may also be historical, cultural, or economic reasons why certain systems are used in certain places which co-exist with the technical justiIication. As with all popular and demanding activities, there are many products in use. One important ramiIication oI this is that students in technical Iields must expect to become Iamiliar and proIicient in more than one programming svstem. Studying more than one brings greater knowledge oI diverse ways oI achieving a goal. It also allows one to Iunction eIIectively as a team member in larger cross-organizational eIIorts and to better to cope with the diversity in computing cultures that's out there. 1.7Why pick Maple as the first system7 1. It is an interactive system, facilitating quick exploration of new ideas. Compared to languages such as C or Java, one can immediately start up an interactive system and calculate results through "point and click" and a little typing. It's also possible to enter computational scripts, which are sequences oI steps that are less elaborate to set up than programs. The scripts can be easily re-run on variants oI the original situation just by changing a line or two in the script. This allows convenient "what-iI" exploration, where a number oI diIIerent scenarios are explored through computation. The worksheet interIace to Maple allows sophisticated mathematical typography and graphics as well as mouse- and palette- driven input. 2. It can handle calculations with formulas. Rather than figuring out the formula yourself, you can even get Maple to calculate the formula for you. While many mathematical calculations produce numerical results, Iormulas are needed to speciIy how those results are produced. Designers or developers oIten need to Iind and create the Iormulas rather than to just copy them Irom a book. A system where Iormulas are easy to represent and easy to create supports this kind oI work. A system that allows you to represent and calculate both numbers and Iormulas makes it easier to do and document technical calculation than a system that just works with numbers. 3. It supports a variety of data structures that support technical computation: Iormulas, equations, Iunctions, sets, lists, tables, vectors, and matrices. Rather than having calculations done with a number oI digits that's Iixed Iorever, it is easy to change the precision iI more (or less) precision is needed. Having higher-level interaction with the computer is usually more productive oI human time. Having all oI these entities as "Iirst class entities" in the system requires less mental eIIort by the user, since they do not have to translate what they are thinking about (e.g. a table oI Iormulas) into the terms that the computer is using. Rather, the computer language accommodates the human style oI thought. 4. It supports documentation as well as calculation. From the instructor's point oI view, it's easier to create documents that explain Maple because we can use Maple both to handle the calculation and the presentation oI results. For students, having a Iile with both the directions that cause the computation and the results makes it easier to present the work cleanly Ior grading, and Ior Iuture reIerence. For proIessionals doing technical work, having an integrated environment where text, programming and results can be combined together can be a convenience. 5. It has a "conventional programming language". An objective oI this course is to make you become Iamiliar enough with some oI the standard elements oI programming (e.g. assignments, conditionals, loops, procedure deIinitions) so that you can use them creatively to handle certain common situations that can't be handled through point-and-click or built-in operations. These elements will be Iound in highly similar Iorm in the languages used by many other systems used Ior technical work. 6. The mathematics of modeling and simulation is an explicit feature of the language. While its programming language is conventional, Maple's language has an important added plus -- you can work over expressions, equations, Iunctions, and other mathematical objects just as conveniently as iI they were numbers or characters. Conventional languages (e.g. Java) can represent arithmetic operations -- multiplication, addition, subtraction, and division -- but aIter that there are special tricks and conversions that you must perIorm to bridge the gap between what is written in the program, and the mathematical ideas that you are trying to use in the model. It's more straightIorward in Maple to represent the mathematical model and the computation based on it. This ease oI expression and comprehension by programmers has a hard-headed dollars and sense payoII. Less programmer time can be spent developing a computation. There is also an eIIiciency advantage to explicit representation oI Iormulae: it is possible to use systems such as Maple to automaticallv improve the quality and eIIiciency oI simulation calculations. This again leads to lower costs oI doing the work. We think these things provide a soItware engineering advantage that will lead most technical computation systems to eventually have such Iunctionality built-in into them. 6 1 Introduction -- Technical computing in the 21st century 1.8Using more than one system Any user oI computers who expects to use them proIessionally Ior design and investigation must expect to eventuallv learn multiple svstems. Using computer applications Ior work is like using tools in a workshop-- you would not expect to use one tool to do all tasks, even iI the tool, like Maple, has "Swiss Army KniIe" capabilities. Features that make it easier to do certain kinds oI things may slow down doing other things. Even when systems overlap in Ieatures, they typically have diIIering philosophies and diIIerent technical strengths, which means that certain kinds oI work may be signiIicantly easier in one system than another. For example, developing something in Mathematica or Maple may be Iine and quick Ior a personal computer, but making the same programming work on a supercomputer may take a lot oI eIIort in a diIIerent language. Yet a work environment with multiple languages need not be overwhelmingly complex. Most systems with major development eIIort behind them (such as Maple and those mentioned in the "section above) have many similarities. What makes things work out is this: at the introductory level, the diIIerence between casual computing and proIessional technical computing is the style oI working (higher emphasis on documentation, justiIication and ease oI reuse), and the use oI language-based commands/programming needed to do the more sophisticated operations in technical work. "Crossing over" to the proIessional mode oI operation means getting over the hurdles oI learning the new style oI work, and learning how to interact with computers in a typical computer language. Once this hurdle is passed, it should take only incremental eIIort to acquire expertise in the second, third, or th technical system. Having Iormal instruction on the Iirst system should provide an explicit introduction into the concepts and the work processes to Iacilitate this. Most systems realize that they cannot be the sole provider oI technical computing services. II Institution A uses Mathematica and Institution B uses Python Ior their work, then iI they expect to use each other's eIIorts, there has to be a way oI interconnecting programs written in one system with that oI another. Thus most systems have interconnections. For example, the Matlab Symbolic Toolkit allows Matlab users to call Maple to do Iormula manipulation. Similarly, Maple users can link to Matlab and run a Matlab program they've gotten Irom a colleague as part oI a problem- solving process written in Maple. Knowledge oI basic programming and the concepts oI software development make it possible to switch between systems with only a modest amount oI additional eIIort. SoItware interconnection allows one to reuse programming done in another system without having to translate into another language. Symbolic computation systems like Maple also have the additional bonus oI being able to translate some oI their programming between languages. There is a "convert-to-Matlab" Ieature Ior example, or a "convert-to-C" Ieature Ior computations involving just numbers or text. 7 2Getting started with Maple's Document Mode: doing technical work with a clickable interface 2.1Chapter synopsis 1. How to start up Maple and perIorm simple calculations, algebra, and plots within it. 2. Detecting and Iixing typographical mistakes. 3. Detecting mistakes caused by misunderstaplondings and incorrect decision making by the user. 4. How to save Maple work so that you can reIer to it or resume working on it later. 5. How to recover a Maple worksheet iI it or your computer crashes. 2.2Starting up Maple, getting a fresh start Start up the Maple application (this varies on the type oI computer system you have, typically it involves clicking or double-clicking on the Maple 15 icon, but iI you can't Iigure it out yourselI ask Ior a demo Ior someone who knows). Once the Maple application window appears, a new document will appear in the main working area oI the Maple application. A Ilashing cursor will appear with the outline oI a small rectangle with dashed lines. The entry mode will read "Math" and "2D Math". You can make the "quick help" black box disappear by clicking on the "close box" circle-X in the upper right hand corner. 8 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Table 2.1: Maple started up with new document in Windows XP AIter you close the quick help box, you will see the Maple cursor in a small rectangle with a dashed line outline 2.2 Starting up Maple, getting a Iresh start 9 Table 2.2: Maple document with first entry area At this point, what you type will appear in the small rectangle and be regarded as a mathematical expression. In the next section, we describe what to type in order to get something useIul to happen. 10 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace 2.3Evaluating an expression involving exact arithmetic Grade school arithmetic In the math area, type 2 + 3. "2 3" is regarded as a mathematical expression by Maple when you type it into the dashed rectangle. As you are typing, the input indicators should say that you are entering Math mode, in "2D Math" input, using "Times New Roman" Iont: Table 2.3: Maple input using 2d math This expression should show up in the work area. When you hit the enter key, then Maple will evaluate the expression. AIter the expression is evaluated, you should see the result displayed below the input, as in the Iigure below: Table 2.4: Maple input with labeled result Maple has automatically calculated the answer and given it a label (1). AIter Maple calculates the answer, the cursor should appear below the result in another dashed-line rectangle. This indicates that Maple is ready to do another calculation. Maple supports all the basic arithmetic operations in a Iashion similar to many other programming languages. One thing that takes some getting used to is that * (asterisk) is used to input multiplication rather than "x" or a centered dot. Another thing that takes getting used to is that what you type is Iormatted to look like math notation. Thus iI you type a /, Maple understands that you are talking about division and immediately starts Iormatting your input as iI it were a Iraction. II you type an asterisk, Maple Iormats that into a dot (). There is also Iormatting that occurs with caret (`) since that is the way you enter an exponent (power) in Maple. Table 2.5: Arithmetic Operations in Maple Operation Character to type/ character name Notes Example addition 2.3 Evaluating an expression involving exact arithmetic 11 (2.1)
multiplication* ("asterisk") Typing an asterisk makes a center dot( ) appear in the displayed expression.
(2.2)
division / ("slash") Typing a slash draws a baseline and then positions the cursor in the denominator. Subsequent typing appears in the denominator. To get out oI the denominator and return to normal typing, use the right-arrow key ().
Multiple divisions are by deIault conducted leIt-to-right.
(2.3) (2.4) subtraction - ("dash" or "hyphen", typically on the same keyboard key as the underscore. Dash and underscore do not mean the same thing.) Multiple subtractions are conducted leItmost Iirst.
(2.5) (2.6) parentheses ( , ) ("leIt parenthesis", "right parenthesis") Use parentheses to change the order oI calculation. They are also good Ior removing any guesswork by the reader as the order oI operations.
(2.7) (2.8) negation - ("dash" or "hyphen", typically on the same keyboard key as the Put a dash in Iront oI a number or parenthesized expression to negate it.
12 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace underscore). This is the same symbol as used Ior subtraction (2.9)
power ` ("caret", typically on the same keyboard key as the number 6) Typing a caret moves the cursor to the exponent position. Subsequent typing appears in the exponent. To get out oI the exponent and return to the baseline, use the right-arrow key ().
(2.10) (2.11) (2.12) (2.13) Iactorial ! ("exclamation mark", typically on the same key as the number 1.) is the product oI all the integers between 1 and n. It is useIul in computations that compute the number oI possible ways that something could happen. For example, the number oI possible orderings oI a deck oI playing cards is 52!
(2.14) (2.15) (2.16)
Let's try out some oI these operations. We can enter a sum oI two Iractions by using "" and "/". II we type "2/35/6 enter", We intWthis is what we see: (2.17) 2.3 Evaluating an expression involving exact arithmetic 13 The way to get a Iraction in is to type a slash (/). As soon as you do so, Maple draws an underscore and positions the cursor underneath the Iraction line. The next characters you type appear as the denominator. II you type the "" right aIter the "3", the plus will appear in the denominator which is permitted by Maple but not what we want in this situation. To get the "" to appear outside oI the Iraction, we type the right arrow kev (the key with on it). This moves the cursor out oI the Iraction back into the baseline oI the expression. Then we can enter the Ior addition, and another Iraction. AIter we hit the enter key, Maple will simpliIy the result into a single Iraction with any common Iactors removed Irom the numerator and denominator Now let's do a multiplication. The Maple programming language (like most) uses an asterisk * as the symbol Ior multiplication. However, Maple displays the expression with a centered dot. This may be disconcerting -- what you type is not what you see. When you are in "math mode" Maple will be using Iancy typography to display whatever math you are entering. We'll see more oI this shortly. See iI you can reproduce this result:: (2.18) We can mix operations. Try to enter and calculate the Iollowing: (2.19) In order to get that last denominator, we had to select the expression we had entered Ior the numerator with the mouse, so that the entire contents oI the entry rectangle were blue. Then we typed a slash and the denominator appeared beneath it all. An alternative to using the mouse to enter expression (1.2.1.18) would be to use parentheses. II we type "(12/345*67)/8 enter" we will see this: (2.20) This allows you to enter complicated expressions without having to use the mouse. OI course, the mouse is still necessary iI you want to go back and edit. We observe in passing that a distinctive Ieature oI Maple is that Maple does exact arithmetic with integers and fractions. It keeps Iractions as the ratio oI two integers. It will, however, automatically simpliIy such ratios to lowest terms: (2.21) Diagnosing typographical mistakes Making mistakes is a normal part oI using any tool, be it a computer or otherwise. You'll probably make as many mistakes learning how to use Maple as you would make when learning a new sport, a musical instrument, or when learning how to write a good essay. Some oI them will be obvious as soon as you make them, others will be subtle or harder to Iigure out how to Iix. When you make some kinds oI mistakes, the computer may give you an error message For example, iI you make a typo and Maple doesn't recognize what you enter as being a valid command, it will complain. Here are some typical error messages. At this stage, some oI the messages 14 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace will make sense and you can react appropriately. Others will use vocabulary that is unIamiliar. For those, the best thing to do is to have a clear idea oI what you want to enter (by closely imitating examples that are known to work) and checking careIully that what you have typed was accurate. Table 2.6: Examples of Maple error messages
Error, invalid sum/diIIerence We intended to enter "2 4" but Iorgot to type the "4" beIore we hit enter (return). The appropriate thing to do here is to correct the expression and hit enter again.
(2.23)
Error, missing operation This time we mistakenly enter the expression with the symbols in the wrong order. Maple complains that it expects some operation to be entered between the two numbers but there isn't one.
Error, invalid matrix/vector product We intended to enter "24" but typed a period instead oI a 2 by mistake. Even though we are trying to do the same thing, the error message is diIIerent because a diIIerent symbol (the period) in this context suggests to Maple that we are trying to do linear algebra. The appropriate thing to do here is to correct the expression and hit enter again.
(2.26)
Error, numeric exception: division by zero 2.3 Evaluating an expression involving exact arithmetic 15
II we ask Maple to do an impossible operation, it sometimes gives an error (depending on the operation). The appropriate question to ask yourselI here is "what should I be dividing by instead oI zero?".
Error, unable to match delimiters We started a sub-expression with a parentheses but Iorgot to Iinish it. In Maple, a delimiter reIers to a parenthesis -- ( or ) -- a bracket | or |, or a brace or }. Delimiters are symbols that mark the beginning and end oI an expression. In many instances they are necessary to unambiguously indicate meaning. For example evaluates to 40, where as the expression without parentheses means 20 because multiplications are always done beIore additions unless the parentheses indicate otherwise.
Error, unable to match delimiters This is another instance oI the same mistake. We wanted to enter but Iorgot a parentheses.
Error, invalid sequence We intended to enter "13" but typed the extra comma in by mistake. We get an error message that talks about sequences, a concept in Maple that we haven't discussed yet (that's coming in the next Iew chapters). Maple thinks that the sequence is "invalid" because it usually expects commas to be between items, such as "1,2,x". Maple's language has many other elements in it that we haven't gotten to discuss yet. II you use any oI them by mistake then you will see messages with vocabulary we haven't discussed yet. It's a Iairly typical experience Ior new users to see some messages that you won't be able to gather much intelligence Irom other than the Iact that you made a mistake that you should Iix,. With knowledge-rich systems such as Maple, you may blunder into sections oI the system that you haven't learned yet. The best strategy is to back out oI the situation by editing the expression so that it is exactly like something that is known to work. 16 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace
Error, invalid Iraction This one is Iairly obvious. In order to Iix it though, we need to know what numerator we intended to enter. We can Iix this by editing the expression with the missing numerator and hitting enter again, as below:
(2.29)
MaplesoIt, the producer oI Maple, provides an on-line list oI all the errors in Maple 15 at http://www.maplesoIt.com/support/help/category.aspx? CID2544. The leIt column oI the page lists all messages. Clicking on a particular message link will produce an explanation that is oIten helpIul in Iiguring out what has caused the message. An on-line list of error messages at http://www.maplesoft.com/support/help/category.aspx?CID2544. Clicking on a message in the left column will display a page about that message.
2.3 Evaluating an expression involving exact arithmetic 17 Correcting typographical mistakes The standard procedure Ior Iixing a mistake is as you would in a word processor: and re-execute the computation. 1. Using the mouse, position the cursor where the mistake is. Then use the backspace key to erase the characters you want to get rid oI. Type in more characters to replace it.. 2. Use the leIt arrow key () to back up. Typing aIter backing up then inserts the new typing at the point where the cursor was positioned. 3. Use the mouse or other "pointing device" oI your computer to select a section oI what you typed. New typing then replaces the selection oI what you typed. 4. Use the mouse to select a region, then "cut", which you can do through the Maple menu Edit -~ Cut. OI course most people use the keyboard shortcut Ior cutting, which Ior Windows or Linux is control-X while on the Mac it's command-X. 5. Copying and pasting (control/command-C and control/command-V) also works in Maple. 18 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace You may Iind that sometimes you attempt to create a 2D Math input area but Maple does not compute a result Ior the input aIter you hit the enter key. To create a "clickable math" input area iI this happens, place the cursor where you want the input area to be, and use the Format-~Create Document Block Menu item oI the Maple window: Table 2.7: Create Document Block to force a Math input area wherever the cursor is placed Exponentiation (powers). Numbers with lots of digits Use a caret ` to speciIy an exponent (a "power"). In math mode, Maple will position the cursor so that the next things you enter will become the exponent. As with Iractions, you can get out oI the exponent by using the right arrow key when you want to go back to non-exponent numbers. Try entering these expressions (2.30) (2.31) 2.3 Evaluating an expression involving exact arithmetic 19 We note that Maple does integer and Iraction operations exactlv. It will not introduce any rounding error into a computation as a calculator would when the answer requires more than ten decimal digits to write down. There are limits to the number oI digits Maple will use Ior integers or Iractions, but they have to do more with limits oI the computer hardware and memory rather than a "pre-ordained" decision about how many digits might be useIul to keep. II you type kernelopts(maxdigits) into a Math input area on the worksheet, Maple will print out a number which is the maximum number oI digits it can handle in any integer or Iraction. On the author's computer in 2011, . This says that the largest number that can be computed by Maple has over 268 million digits. Even iI we wanted to use the answer, we wouldn't want to look at For example, Maple can compute the result oI exactly (try it!). Exact computation is useIul not only Ior doing algebra but also Ior things such as computing probabilities through counting, or in deriving mathematical Iormulas Ior use in simulation or prediction programs. Detecting and fixing semantic and "logic" mistakes There will be other kinds oI mistakes where there is no error message, but the response is not what you want. Sometimes this happens because you say something that while grammatical, means something entirely diIIerent Irom what you meant. This kind oI mistake is called a semantic error. This could be as simple as entering "2-3" where you meant to type "23". Sometimes it is less obvious, such as mistyping the 23-rd digit oI a 55 digit number or the 12th term oI a long sum. Or worse yet, it could be because vou are using the incorrect vocabularv so what you think you are saying does not have that meaning to the computer. Table 2.8: Example of a vocabulary mistake (2.32) Suppose we were under the (mistaken) impression could use "x" in Maple to stand Ior multiplication. We might use the above as a way to calculate "two times three, plus Iive". However, while there is no error message, what is calculated is not the number we were expecting. The Iirst step towards proceeding to Iix this is to realize that it's not what we want. To Maple, this is a legitimate calculation -- you want to create a Iormula that's "two times the variable x3, plus Iive".
(2.33) Knowing that the proper way to enter multiplication is through a palette, or symbol "*" (asterisk) as explained in XXXX.
(2.34) 20 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace (2.35) (2.36)
Maple allows you to write any oI these things, but they mean diIIerent things to it. Maple's grammatical rules requires you to speciIy multiplication by use oI the explicit mark Ior multiplication, or the use oI the Palette item as described in the section "The Expression Palette" later in this chapter. The use oI "x" or just juxtaposition doesn't mean multiplication in Maple -- these are not errors, they mean something else other than multiplication (Iunctional composition, to be precise, although Ior our purposes it's easier to just think "doesn't mean multiplication"). Finally, there are mistakes made because vou ask Maple to do the wrong calculation. Even though Maple does what you want, it turns out that what you wanted was wrong! For example, you may read a word problem and decide to solve the equation whose solution is x4/3. But when you plug the solution into the circumstances oI the problem, you Iind that it doesn't solve the word problem. The problem may be because your decision that was the equation when it should have been This is known as an "error in logic" or just a "logic error". Sometimes it's obvious that you made a mistake because the answer is obviously wrong. For example, seeing "-1" as the answer to "how many eggs did the chickens lay in three days?" is obviously wrong since there's no such thing as "negative eggs". Sometimes you can plug your solution into the original situation to see iI it works asit should. 2.4Saving and retrieving your work You can save your work in a Maple worksheet Iile through the File -~ Save (keyboard shortcut: control/command-S) menu item oI the Maple application. A dialog box appears allowing you to type in the name oI the worksheet (we've typed in "test" into the box in the .) The Iile is saved with a ".mw" suIIix (e.g. test1.mw). To retrieve the Iile in a subsequent Maple session, start up the Maple application as beIore and then use the File-~Open menu item to initiate the dialog that retrieves the Iile. 2.4 Saving and retrieving your work 21 Table 2.9: Maple save menu operation 22 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Table 2.10: Maple save dialog box 2.5Retrieving backups The "state oI Maple" display appears on the bottom leIt hand side oI the Maple window. Usually this display says "Ready", which means that Maple is awaiting your next command. Sometimes it reads "Evaluating..." which indicates that Maple is actively computing an answer. Sometimes it says "Autosaving worksheet", which means that it is saving a copy oI the present state oI your open worksheets into temporary storage on your computer. The amount oI time Maple spends autosaving becomes noticable in longer Maple sessions when the worksheet contains a lot oI results. Should your computer suddenly lose power or should Maple crash, you can retrieve the last autosaved worksheet by selecting the File -~ Recent Documents -~ Restore Backup menu item. This will Iill your Maple with copies oI all the autosaved worksheets. You may then delete them or save them to permanent Iile space as you wish. 2.6 Algebra, plotting and mouse-clickable operations 23 Table 2.11: The Maple state display 2.6Algebra, plotting and mouse-clickable operations Algebraic expressions and equations. Solving equations. Working with pieces of expressions. We don't have to limit ourselves to just numerical calculation in Maple (even iI the ability to use as many digits as we wish and exact Iractions allows us to do arithmetic more like the math books do). Another distinctive Ieature oI Maple is that you can do algebra by entering expressions with symbols -- the x,v,:, i, and n that we see in algebra books. Maple will automatically collect terms and do some simpliIications Ior us automatically (2.37) We can even enter equations: (2.38) (2.39) Note that while Maple automatically collected the x terms on the leIt hand side oI the equation, it does not try to do the more interventionist operation oI moving all the x terms to the same side oI the equation. Now, enter the Iollowing expression, but rather than hitting the enter key aIter you've entered it, do a right-click. On the Mac, instead oI right- clicking hold the control key down then click on the mouse button (this is reIerred to as "control-click".) A menu oI algebraic operations will pop up. Select Factor and see how Maple can Iactor the polynomial: 24 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Note that this line does not have a (XX) label Ior it. To Iurther demonstrate the right-click (control-click) operations available, enter the Iollowing equation. Right click on the expression and a pop- up menu should appear that includes a "solve" item. Select the solve and a submenu will appear where you can speciIy that you want to solve Ior x. For those with previous experience on other systems: some things are different, for a reason (This section is Ior people who already know a programming language and are noticing that Maple does some things diIIerently. Other readers can skip this section.) Most mainstream programming languages work in a similar way. That is why learning Maple has value beyond just being able to use the Maple system -- once you learn Maple, learning Matlab or Java or C is a matter oI incremental adjustment.Noticing the diIIerences is educational in that it makes you become aware oI the arbitrariness oI some oI Ieatures oI languages. II you have used another programming language such as Java or Visual Basic (VB), you will notice that some things do not work the same in Maple as they do there. Some oI this can be explained iI you know something about the history oI programming languages. Some oI it is explained by being aware that the designers oI Maple had diIIerent goals than those who invented Java or VB. One thing that you have undoubtedly noted is that symbols do not have to have a value associated with them. For example, in Java iI you said k5; Then iI you were to create another expression in Java such as System.out.println(k^2 + k + k + 3); then "5" would be used as the value oI k in the expression and you would end up printing 38. In Maple, you do not have to associate k with a numerical value beIore you use k in an algebraic expression. II there is no prior association, Maple just treats the expression as a Iormula with symbols in it. It may do some algebraic simplification on what you entered, but it does not need to get a number as a result. Since there was no prior assignment Ior the expressions in section 2.5.1, the calculation done with them just keeps the Iormula.. Another thing that is diIIerent is that in Maple "" is used for equations, not assignment.. The operator in Maple corresponding to "" in Java or VB is ":" (a colon immediately Iollowed by an equals, with no spaces inbetween). In Maple, iI we wanted to associate "5" with the symbol k, then we would do: (2.40) (2.41) People who know more than one programming language have a better understanding oI which Ieatures are change a lot between languages, (such as whether or : is used Ior assignment), and which ones are Iairly uniIorm ( being used Ior addition, or the use oI parentheses in Iunctions and expressions). Maple does not use "" Ior assignment because, being a mathematically oriented language that can handle algebra, it wants to make the entry oI equations a natural thing. Its use oI ":" Ior assignment is a Ieature borrowed Irom the Algol/Algol 68/Pascal Iamily oI programming languages, which picked this operator to make it clear that the assignment operation is diIIerent Irom algebraic equality. 2.6 Algebra, plotting and mouse-clickable operations 25 Is ":" better than ""? That's a kind oI question that is about as hard to answer as trying to decide whether "uno" is better than "one". II one had a language where you had to do ":**&`#*" instead oI "" or ":", you could be critical oI the choice because it takes much more eIIort to enter a 35 character operator than a one or two character one. But the Algol-Iamily choice oI ":" has reasonable motivation -- studies oI novice programmers have shown that beginners using languages where "" is the assignment make more mistakes because they conIuse its use in mathematics with its use in programming. Novices have been observed to write things like "5k" which does not work as an assignment, even though mathematically the equations "k5" and "5k" mean the same thing. Just as with architectural design oI a building, each Ieature oI a programming language is typically careIully considered. Many Ieatures are borrowed or copied Irom predecessor languages, where they have already been subjected to the test oI many people using the Ieature. II you are not Iamiliar with Algol Iamily languages, you can see examples oI them at various educational web sites, such as http:// www.engin.umd.umich.edu/CIS/course.des/cis400/algol/average.html and http://portal.acm.org/citation.cIm?id154766.155365. Plotting, approximate numerical solutions through cursor position The right-clickable interIace can also activate a plot oI a Iormula you may have entered. Enter this Iormula, then right-click and select Plot -~2d plot. The automatic deIaults Ior plotting this produce this result. Table 2.12: Example of Plotting
26 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Table 2.13: Plot created by right-click -> Plot -> 2DPlot (with cursor positioning)
The user has clicked on the plot and positioned the cursor at the coordinate (-4.12, 61.60). The cursor was not captured by the screenshot although it is visible under ordinary use.
The 2DPlot operation makes pre-set decisions about the plot, such as the range oI (-10 to 10), the color oI the line, axes labelling, etc. Users can inject their own preIerences about these things about this by selecting right-click -~ Plot -~PlotBuilder and Iilling in the dialog box with their choices. 2.6 Algebra, plotting and mouse-clickable operations 27 Table 2.14: User-configured plot using PlotBuilder instead of 2DPlot
Table 2.15: PlotBuilder Dialog box
28 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace
The Expressions Palette and the Common Symbols Palette: entering Trigs, logs, roots, exponentials It's possible to get the common Iunctions oI high school algebra, pre-calculus, and calculus by using the Expression palette oI the Maple Window: Table 2.16: The Expression palette
For example, to enter the square root oI 36, click on the palette entry Ior That expression will appear in the document, with the "a" selected. II you then type 36 on the keyboard, that number will replace the selected text. II you then hit the enter key, Maple will evaluate the expression and produce the exact result "6". 2.6 Algebra, plotting and mouse-clickable operations 29 (2.42) You can use the palette multiple times, to create more complicated expressions. Just continue to the use mouse or the arrow keys to move around in the expression. Selecting and typing, backspacing or deleting are all ways oI replacing or correcting pieces oI the expression. The Common symbols palette, two panels below the Expression palette, can be used to enter a and , the base oI the natural logarithm system. The palette does not have the inverse trig Iunctions, so you have to enter them through typing. Their names are: arcsin, arccos, arctan, etc. Table 2.17: Examples of palette-driven computation
(2.43) (2.44) (2.45)
Approximate numerical (calculator - type) arithmetic in Maple II you enter expressions with integers, exact Iractions, and symbols such as a and . then Maple will perIorm exact calculations rather than give approximate answers as a conventional calculator would. You can get approximations by selecting the "numerically solve" instead oI the "solve" option Irom the right-click pop-up menu. Table 2.18: Examples of computing with approximate solving
Exact solution oI an equation using the "solve" Ieature oI the pop-up menu. 30 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace
Using the "numerically solve" Ieature oI the pop-up menu II you have an exact expression, you can ask Maple to approximate it to 5, 10, 20, or more digits. In this mode, Maple can be used as a super- accurate calculator. Examples of numerical computation 1. Enter Iraction, select approximate-~20 Irom right-click pop-up menu. 2. Enter exact expression, select approximate-~5 Irom right click pop-up menu 3. Enter equation. Then solve-~solve, then select Element-~1, then right hand side, then approximate-~10
Evaluation, and selection of pieces. Sometimes you wish to evaluate an expression for a particular value of a variable. There is a right-click operation that does this. Table 2.19: Evaluate at a point
This operation will give a pop-up menu that will allow us to choose values Ior all the variables. In the Iirst example, we we picked 1/2 Ior a value oI x. Note that the pop-up menu will show what you typed rather than displaying 2D math. In the second example, we speciIied "3*y`2" as the value Ior a. In the third example, we picked 3 as the value Ior y. 2.7 A quick-reIerence summary to this chapter 31
Using the right-click menu, it's possible to select or extract a portion oI an expression Ior Iurther work. Table 2.20: Operations on equations, multi-part expressions right hand side, leIt hand side
One oI the options in the right-click menu is "right hand side". It only works Ior equations. Operations on multi- part expressions
Example
select entry
Solving this quadratic equation reveals that there are two solutions. Right- clicking on the solution and then selecting entry 1 gives the Iirst solution, enclosed in brackets | |. Right-clicking on that and again selecting entry 1 gives the Iirst solution, without the brackets. Right-clicking on that and selecting approximation gives a calculator approximation to the root. 2.7A quick-reference summary to this chapter Example Description Notes Arithmetic
(2.46)
Use , *, -, /, ` Ior arithmetic. Hitting the Enter key produces a labelled result. 2 D Math input mode displays the textbook-like version oI what you input. Maple's simplification automatically combined Iractions and places things in lowest terms. Use ! Ior Iactorial Do you know what 5!! (double Iactorial) means? 32 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace (2.47)
Making mistakes
Error, unable to match delimiters
Error message mistakes (Irom typos or mistakes in intensions) The easiest ones to detect. You have to Iigure out what you are doing wrong, though. The error message may not always be helpIul in advising you on this, although it oIten is. A Iarmer plants a Ience post every Ioot, Ior 1250 Ieet. At that point, he switches to planting the Ience posts every 4.7 Ieet Ior another 940 Ieet. How many Ience posts does he need in all?
(2.48)
Maple did the arithmetic in the above calculation correctly. But it's not the solution to the problem. Do you see how to get the right answer? "Logic errors" OIten you can Iind these kinds oI mistakes by looking at simpler versions oI the problem where the answer can be Iigured out with paper and pencil. For example, sit down and draw a picture oI the posts and their positions when the initial distance is 10 Ieet, and the second distance is 9.8 Ieet. Count the posts in your picture. Then you "scale up" the calculation to handle the large situation.
It's easy to compute the wrong answer in these kind oI "oII by one" situation. Editing (fixing mistakes) backspace, delete erase starting Irom current cursor selection
Arrow keys move cursor within current selection
Select with mouse/type replaces selected text
Cut, copy and paste oI a selection works as it does with a text processor
File saves, opens 2.7 A quick-reIerence summary to this chapter 33 Save Iiles with File -~ Save or File -~ Save As. Open a saved Iile with File -~ Open. Other File operations are similar to that oI standard word processors.
Functions and math symbols
(2.49)
Insert math into an expression by using the Expression Palette. You can enter using the Common Symbols Palette. (the natural logarithm base) can also be entered this way. Note: typing e Irom the keyboard does not enter this symbol.
Chapter 2 demonstrated the Iollowing Iunctions and symbols Square roots, n-th roots natural logarithms (base ) Trig Iunctions: sin, cos (trig Iunctions Base 10 logarithms all use radians, not degrees) arcsin, arccos, arctan sec,, csc summation a,
II you are entering a Iunction by the keyboard rather than the palette, you must enclose the Iunction's argument in parentheses.
Algebra
Right-click (control-click on Mac) on an entered expression to get the pop-up menu. Chapter 2 demonstrated examples oI the Iollowing operations: Iactor solve solve numerically right hand side (oI an equation) leIt hand side (oI an equation) select (n-th part) oI an expression approximate numerically (to 5, plot (two dimensional) -- many plot options 10, 20, etc. digits' accuracy) to determine range and domain oI plot, color, captions, etc. evaluate at a point (choose values
Ior variables in an expression)
34 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Plotting Plots-~2d plot
The expression must be something that involves a single variable and will result in a number when a value is used Ior that variable. Thus you can't do a 2d plot oI because you wouldn't get a number iI you picked a value just Ior x (or just Ior a).
Maple uses deIaults Ior the plot range, and the plot color.
Trying to plot an equation produces an implicit plot (see next appendix). Plots-~plot builder -~ 2d plot
A dialog box appears that allows you the select Irom many more options, such as plot color, the line style, vertical and horizontal ranges, captions, etc. Limited precision (decimal point) numbers
Exact numbers in Maple have no decimal points. Symbolic constants such as a and entered Irom the Common Symbols Palette are also exact. Use oI limited precision numbers in algebra (e.g. Iactoring, diIIerentiation, solving) may not produce good results.
2.7 A quick-reIerence summary to this chapter 35 (2.50) (2.51)
Numbers with decimal points in Maple cause arithmetic calculations to be done approximately.
.right-click-~approximate-~n takes an exact numerical expression and approximates it.
Use them in Maple only when an approximate result is desired.
Numbers like .25 or .6015 are limited precision. II you want exact algebra done, use 1/4 or 6015/10000, etc.
In very large calculations, limited precision calculations may be noticably Iaster than those with exact arithmetic. Most oI the time there isn't an appreciable diIIerence. Evaluate at a point Example
This operation will give a pop-up menu that will allow us to choose values Ior all the variables. In the Iirst example, we we picked 1/2 Ior a value oI x. Note that the pop-up menu will show what you typed rather than displaying 2D math. In the second example, we speciIied "3*y`2" as the value Ior a. In the third example, we picked 3 as the value Ior y. Operations on equations Example right hand side, leIt hand side
One oI the options in the right-click menu is "right hand side". It only works Ior equations. Operations on multi-part expressions
Example
select entry 36 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace
Solving this quadratic equation reveals that there are two solutions. Right clicking on these selections and then select entry -~ 1 produces the Iirst solution. We can then approximate it by using the Enter an expression in a document , then right-click (control-click on Mac) followed by: Commentary Operations on symbolic expressions Example solve-~solve
solve-~solve Ior a variable
solve-~numerically solve
The thing to try when there is a numerical answer but the exact solution is too complicated to understand or Maple can't Iind an exact solution. Factoring
Factoring can simpliIy an expression sometimes. Factoring doesn't know the trig simpliIication rules, though. Plots-~2d plot
The expression must be something that involves a single variable and will result in a number when a value is used Ior that variable. Thus you can't do a 2d plot oI because you wouldn't get a number iI you picked a value just Ior x (or just Ior a).
Maple uses deIaults Ior the plot range, and the plot color. 2.7 A quick-reIerence summary to this chapter 37
Plots-~plot builder -~ 2d plot
A dialog box appears that allows you the select Irom many more options, such as plot color, the line style, vertical and horizontal ranges, captions, etc. 38 2 Getting started with Maple's Document Mode: doing technical work with a clickable interIace Operations on equations Example right hand side, leIt hand side
move to right, move to leIt
This moves the entire side oI an equation to the other side. Operations on constant expressions Example approximate-~5 (or 10, 20, 50)
Uses approximation methods to turn constants into an approximate (decimal point) number with 5 (10, 20, 50) digits. 39 3Chapter 3 Technical word processing 3.1Chapter Overview In this chapter, we learn how to use Maple as a word processor. This allows us to write reports that combine technical writing with math Iormulae, calculated results, pictures, tables, etc. Many oI the Ieatures are highly similar to MicrosoIt Word or similar WYSIWYG (what you see is what you get) word processors. The strength oI Maple's word processing is that it makes it easy to enter technical Iormulae, and that the word processing and calculation can be done in the same document. 3.2Maple as a word processor Maple documents allow a mixture oI text and mathematics. By deIault, Maple expects that when you position the cursor by clicking somewhere in the document, you will be entering math and be wanting it do to a calculation. The document is in what is called math entrv mode. Table 3.1: Maple in math entry mode
You can tell whether the document is in math entry mode because the Math button on the Maple toolbar will be gray, and the "C" menu item says 2D Math. 40 3 Chapter 3 Technical word processing Another mode oI operation Ior Maple documents is text mode. When in text mode, Maple has the behavior oI a word processor. It just shows what you typed. Hitting enter while you are in text mode just causes text entry to move to the next line. It does not cause any calculation to be done with what you typed. You can switch to entering text in the Iollowing way: 1. Position the cursor at the spot where you want to enter text. 2. Click on the Text button on the Maple toolbar. This places the Maple document in text entrv mode. Alternative you can switch to Text mode by typing control-T (on Macintosh, command-T) or by using the Maple menu bar Insert-~Text. You can tell when you've switched to text entry mode because the Text button will be gray, and the "C" menu item says Text.. 3. With the keyboard, enter your verbiage. When you are in text mode, you will also see that the menu bar will be enabled Ior boldIace, italics, underlining, leIt-/center-/right- justiIied text, colored text, and colored backgrounds, and bulleted/numbered text. 4. To switch back to math,click on the Math button on the Maple tool bar. Alternatively you can type control-R (on Macintosh, command-R), or use the Maple menu Insert-~2-D Math. Table 3.2: Document after control-T (or Insert->Text)
3.2 Maple as a word processor 41 A Maple worksheet in text mode in OS X. Although it is hard to see, the cursor is positioned at top leIt oI screen. You can do mathematical word processing without any computation by switching between text and math modes, using the Palettes to help you enter the math. As long as you don't hit the return (enter) key, the math will not cause any calculation. Table 3.3: Document with a mixture of text and math
The user typed the text, then went into math mode by typing control-R (command-R). They then entered the "F G..." Iormula in math mode. The user got the subscripted by typing an underscore _ aIter the m to get Maple to descend to subscripts, then used the right-arrow key to ascend back up to the main level oI the expression. The other symbols in the midst oI the rest oI the narrative are entered in a similar way.
It is possible to mix text and the results oI calculations in a paragraph. Typing control- (command-) when the cursor is in a math expression will cause Maple to print an "" and then the result oI evaluating the expression on the same line. This is an alternative to hitting the enter key and allows those kinds oI calculations to be mixed with text. 42 3 Chapter 3 Technical word processing Table 3.4: control- puts the results of a calculation in the midst of text
The user entered text, then did a control-R (command-R), then entered the math expression and then typed control-. AIter the calculation result appeared, they typed control-T and entered the remainder oI the sentence. 3.3Shortcuts to entering math symbols Using the Palettes, we can enter a wide variety oI mathematics -- expressions, math symbols, Greek letters (using the Greek Palette), arrows, etc. There are additional Palettes not shown by deIault, which you can get by View Palettes Show All Palettes. However, you can enter many symbols in math mode Irom the keyboard through "shortcuts". Most oI the shortcuts consists oI typing the textual name oI the symbol or some abbreviation oI it, and then hitting the escape kev -- the key labelled Esc on many keyboards. For example, to enter the symbol while in math mode, you can type infin and then hit the escape key. A pop-up menu oI choices will appear to allow you to complete entry oI the symbol. With practice, this can be a Iaster way oI entering than using the Palettes. Table 3.5: Keyboard shortcuts in math mode through the escape key In math mode, we type infin. AIter hitting the escape key, a menu oI completions appears. We pick the Iirst alternative (either by hitting the return key or by operating the mouse to select the Iirst option) and what we typed is replaced by the selection. Greek symbols can be entered by typing the romanized name oI the letter, Iollowed by escape. For example, in math mode, typing omega Iollowed by escape produces . Typing Omega Iollowed by escape produces (the upper case version oI the Greek letter). 3.4 Other word processor Ieatures 43 A shortcut to entering the svmbolic constant e (the base oI the natural logarithm) is to type e, then hit the escape key, then return. You can see a summary to all oI the conveniences Maple oIIers through Help Quick Reference . 3.4Other word processor features Inspection oI the worksheet toolbar reveals many more word processing Ieatures: line justiIication, bold Iace and italics, numbered items, colored letters or backgrounds, Iont sizes, and Iont types. The Insert operation on the Maple toolbar allows creation oI Tables and Images (graphics Iiles). Rudimentary drawings can be inserted through Insert Canvas. We encourage you to explore and make use oI the Ieatures on your own. 3.5Troubleshooting word processing A phenomenon that you may encounter is not being able to switch back to math mode from text mode, even aIter perIorming the operation that should do so (clicking on the Text button oI the document toolbar, typing control-T, perIorming Insert 2DMath, etc. This may be due to the worksheet losing track oI where you are in the document. A "sure-Iire" cure Ior switching modes is to position the cursor at the point where you want to enter math, then do Format Create Document Block. A dashed box will appear at the location oI the cursor, indicating that it is again in math mode. Tools-~Spellcheck (alternatively, the F7 key) will run a spelling check on the non-math part oI your document. 3.6Summary of Chapter 3 material Name Menu operation Key short cut Important word processing operations in a Maple worksheet Switch entry to 2D Math mode Insert-2D Math Click on "Math" oval in menu bar just below names oI worksheets. control-R (command-R on Mac) Switch entry to Text mode InsertText Click on "Text" oval in menu bar just below names oI worksheets. control-T (command-T) Use a keyboard shortcut in Math mode Type the shortcut, then hit the escape key. For example, typing omega and then escape will turn the text into . Typing e and then escape will allow you to turn the text into the symbolic constant without needing the Expression Palette. 44 3 Chapter 3 Technical word processing 45 4Chapter 4 Assignment 4.1Chapter Overview We learn how to label results with symbolic names through the operation oI "assign to a name", sometimes called assignment. This allows us to reuse the results in subsequent steps oI a multi-step calculation without re-entering or copying it. Assignment causes a portion oI computer memory to store the computed result, so that it can subsequently be reIerred to by name. Reassignment changes what's stored. The keyboard operation : provides a keyboard shortcut Ior assignment. : will be used heavily in later work in programming as we shiIt Irom mouse/menu operation to textual speciIication oI calculations. unassign causes Maple to Iorget the association oI value with name. All assignments can be Iorgotten through restart. 4.2Assignment: remembering results for future use We can compute a result and label it with name. This action is called assignment.. We can do this with the clickable menu by the action right-click (control-click on Macintosh) assign to a name . A pop-up menu will appear asking us to Iill in the name that we want to use. Once we have assigned a result to a name, we can use the name, and Maple will use the assigned value. A name can be any sequence oI upper- or lower-case letters, digits and the underscore character _ . It must start with a letter. Maple distinguishes between upper and lower case letters, so result and Result are considered diIIerent names. In programming, the term variable is used interchangeably with name. Both reIer to an identiIier which the action oI assignment associates with a computed result. Computer books oIten talk about "assigning the result to a variable" which means the same thing as "assigning the result to a name". Table 4.1: Assignment (4.1) (4.2)
AIter computing a result, we assign it to the name trigResult by clicking on the result, selecting the menu item assign to a name and then typing in the name. (4.3) (4.4)
We can then use the name instead oI repeatedly entering or copying expressions. 4.3:= is a keyboard shortcut for assignment The Maple operator : (colon immediately Iollowed by an equals) also perIorms assignment 46 4 Chapter 4 Assignment Table 4.2: : is another way to do assignment of a name Form Examples Commentary name : expression whose value will be assigned x : 5 Assigns the name x the value 5. Assigns the name polv the value consisting oI whatever the assigned value oI : is. II no value has been assigned the name :, then the result is the algebraic Iormula: When you enter an expression in Math mode (even iI it's just a name, without any arithmetic), you ask Maple to evaluate what you have entered. Maple also (beIore it does anything else) Iigures out the values assigned to names that appear in the expression. Then it does arithmetic, Iunction calculation, and any other operations you've described in the expression. The only exception to the "Maple always evaluates beIore assignment" occurs when with the name that appears on the leIt hand side oI :. That name is not evaluated, it literally is used as the name assigned to. Assignment really requires two steps. The Iirst is Iiguring out the result. The second is assigning the result to the name. The "Iiguring out the result" step is called evaluation. II any oI the symbols in the expression being evaluated have an assigned value, then that value is used. .II those values involve other symbols, those are in turn checked Ior values, etc.. Symbols without an assigned value have their own names as their value. This allows you to enter an expression such as in x and use the x's as symbols in the normal mathematical style as long as you don't assign x a value. II you use a name/variable in an expression, and it has no assigned value, then Maple uses the rule that the value oI an name with no assigned value is just the name itselI. To deassign a variable use unassign. For example, unassign(x) causes any value oI x have no assigned value, just as iI it had never been assigned. This does not undo the eIIects oI other computations done while the assignment was in eIIect , as the Iollowing examples below illustrate. Table 4.3: Assignment Examples of assignment with : Commentary
(4.5) We assign the name p the value oI the expression. Note that since x and a have not been assigned values, the results oI evaluation just leaves them as symbols. (4.6)
II we enter an expression containing p, its value is plugged in Ior the calculation oI the result.
(4.7) Here we assign the name x the value 3.
4.3 : is a keyboard shortcut Ior assignment 47 Examples of assignment with : Commentary
(4.8) (4.9)
II we now do a calculation with p, the value oI x is used since p's value mentions x. There may be a chain oI assignments that Maple must look at to evaluate an expression.
We can solve the result 1.3.4 Ior a by right clicking that expression.
(4.10) (4.11) (4.12)
We change the value oI x by assigning it a diIIerent value.
When we do another calculation with p, the most recent assigned value oI x is used.
(4.13)
This a way oI assigning 4 -- the current value oI x to the name v.
(4.14)
We can undo the connection between x and any value by unassigning x. This operation produces no output, so no label. We can barely tell that it has happened. The quote marks surrounding the x -- 'x' are mandatory, otherwise x would be replaced by its value and Maple would try to unassign the corresponding value rather than x itselI.
p still has a value, but since x no longer has a value, we are back to the original result.
(4.15)
We may have unassigned x, but y's unassigned value -- 4 -- is unaIIected. The assignment just connects the name and the value determined when the assignment was perIormed (back at (4.13)). The inIormation about which variables or expressions were used to Iigure out what the value was is not retained. 48 4 Chapter 4 Assignment 4.4The Variables Panel: a way to know the current value of your variables The operation oI assignment uses part oI the computer's memory to remember an association oI a name with a result. II you are doing several assignments, you can see the current state oI the Maple session -- the associations oI names with values currently in eIIect -- by using the Variables Panel. It will list all oI the variables assigned, and their present value. A useIul way to think about assignment is to think oI the computer creating a memory slot containing the result, labeled with the name being assigned to. Table 4.4: The variables panel shows currently assigned variables AIter assignment, the Variables Panel shows that the variable p is assigned an expression. II we then assign x a value, then there are two variables listed. Notice that the value oI p is unchanged.
Changing the value oI x doesn't change the value oI p either. However, in evaluating p (which is what happens when you enter "p" into the worksheet, Maple will always use the current value oI whatever 4.5 DiIIerences between the appearance oI the worksheet and the state oI a Maple session 49 symbols are used. II the symbol has no assigned value, then the name oI the symbol is its value. II we unassign a variable, then we can think oI the slot as being deleted Irom the computer's memory. Unassigning x does not unassign p or change p's assigned value. However, the results oI evaluating p changes due to the unassignment since it reIers to a variable whose assigned value has been removed.
4.5Differences between the appearance of the worksheet and the state of a Maple session The state of a Maple session consists oI all the variables that are currently assigned, and what their values are. The state changes every time we do another assignment or unassignment. Only an assignment operation (or an unassignment) can change the state oI the session. The Variables Panel displays the state. Typically work in a Maple document progresses in a top-to-bottom Iashion -- additions are placed at the end oI whatever is already there. This is also true Ior an ordinary word processor such as MicrosoIt Word. However, a key Ieature oI a word processor is that iI you need to go back and Iix something, you can do so. In a Maple worksheet, iI you go back and change a line. However, while this will change the instructions, Maple will not automatically update the results due to the changes. You have to hit enter on the lines you want to be re-calculated. When you save a Maple worksheet as described by Saving and retrieving vour work (page 20)does not save the state oI assigned variables. This means that when you reopen a saved worksheet, no variables are assigned. This can be conIirmed by looking at the Variables Panel aIter reopening a worksheet, as illustrated by the "The state oI a Maple Session" example, below . When you reopen a saved worksheet, it's not "what you see is what you get" -- at least, not right away. To repeat: a saved worksheet does not save the state oI the session (the variable assignments). Opening a saved worksheet Iile does not cause it to automatically execute the operations in the worksheet. This gives you a chance to edit the worksheet to change the calculations speciIied, beIore carrying out the instructions. We know that we can jump back and execute a line in the worksheet a second time, just by positioning the cursor there and hitting enter (return). Thus the way that the document looks is not an accurate reIlection oI variable assignments that current exist in the session. 50 4 Chapter 4 Assignment The Variable panel oI the Maple worksheet indicates which variables are assigned, and what their assigned values are. Use it to determine the current state iI you are not sure what it is. Table 4.5: The state of a Maple Session Example
We took the work oI the previous section and saved it as a worksheet named Start1.mw. We then closed the worksheet. In a Iresh Maple, we opened up the worksheet again. Note that while all the work we did is displayed, the Variable Panel indicates that no variables are assigned when the worksheet is read in. When the Start1.mw, the cursor is positioned in the Iirst line. II we hit enter, we re-execute the Iirst line again. Note that the Variable Panel now has the result oI the Iirst line -- assigning p a value.
4.5 DiIIerences between the appearance oI the worksheet and the state oI a Maple session 51 Example AIter hitting enter the Iirst time, the cursor moves to the second line -- "x : 3". Hitting enter again, causes the second assignment to occur. II we now go back and position the cursor on the Iirst line and hit enter again, p is assigned a value that reIlects that Iact that x has an assigned value.
52 4 Chapter 4 Assignment Example II we then execute the rest oI the lines oI the worksheet by hitting enter some more. But the results are not the same as in the previous example. This because the state oI variables was diIIerent when we executed the Iirst line the second time. In general, re-evaluation oI an expression will yield diIIerent results iI the variables it mentions have diIIerent values than the Iirst time it was evaluated. 4.6restart causes all variables to be deassigned We've seen that it's possible to erase an assignment using unassign. II you want to Iorget all assignments we've made so Iar, then you can use restart. This can be useIul in situations where you've done some work and made some assignments, but now want to switch to working on a diIIerent problem and would like Maple to Iorget about the assignments you made beIore. It is generally a good idea to restart at the beginning oI unrelated sections oI the worksheet just in case variables were previously assigned values that might not be related to their use in the new section. Table 4.6: Evaluation of expressions involving assigned variables Examples of assignment with :
4.6 restart causes all variables to be deassigned 53 Examples of assignment with : We saved a worksheet similar to that oI the previous example, but we placed a restart instruction at the beginning oI it. We executed all the instructions oI the worksheet, in order, by hitting the "!!!" icon at on Maple toolbar. Note that only p is assigned a value at the conclusion because we unassigned x.
We got the worksheet to look like this by executing the x :3 line, then every line starting with (but not the restart). The eIIect oI executing the assignment to p once x had a value causes p to be assigned the result oI evaluating the expression with x's value as 3: . Since this Iormula no longer has any x in it, reassigning x to have a value oI 4 doesn't really change the result oI evaluating p, unlike the previous examples.
54 4 Chapter 4 Assignment Examples of assignment with :
However, iI we re-execute the entire worksheet, including the restart, we have results identical to what we had when things were Iresh. restart removes any inadvertent side-eIIects that old assignments may have on evaluation.
4.7Evaluation and chains of assignments Evaluation always uses the current assigned value oI a variable. Evaluation will Iollow the chain oI assignments to Iind values that does not mention any assigned values. Table 4.7: BROKEN - MISSING TITLE! Examples of assignment with : Commentary We start Iresh through restart. . We assign the name p the value oI the expression, then x. When we assign result2, it evaluates p, and Iinds it to have the value . But x's value is 3 and a's value is y. It uses 3 and y in the 4.8 Troubleshooting assignments 55 Examples of assignment with : Commentary evaluation. This is why result2's assigned value is not the same as that oI p.
II we then a : z 1, then Variable Panel shows that the value oI a has changed, but the values oI p, result2, and x have not. However, iI we ask Maple to evaluate p, the evaluation uses the value oI the symbols mentioned in the value oI p. This is why the evaluation oI p is diIIerent -- , even though the assigned value oI p continues to be what it was originally.
4.8Troubleshooting assignments Equations are not the same as assignment Assignment is an operation that many programming languages have. In some languages (e.g. Maple, Pascal, EiIIel, MuPad) := is used Ior the assignment operation. In others (C, Java, Matlab) = is used as the symbol Ior assignment. Maple uses : because it uses = Ior equations. It would be conIusing to computers and to human readers to use the same symbol Ior two common but diIIerent operations in a single language. and : mean different things in Maple Example
56 4 Chapter 4 Assignment We assign a the value 3. However, Ior the next line we type "x4". This is an equation and it doesn't assign x any value. The Variable Panel shows this because it lists a as the only variable that has an assigned value.
We edit the x4 line into x :4, and hit the enter key. This time the assignment goes through. The name to be assigned always goes on the left hand side of the : Since 5 x and x 5 mean the same thing as mathematical equations, some people think that this should mean that x : 5 and 5 : x should both assign the value 5 to x. However, only x : 5 does the assignment. Table 4.8: Assignment : is not symmetric Error, illegal use oI an object as a name
This doesn't mean anything to Maple. The name is supposed to be on the leIt hand side. (4.17)
This assigns x the value 5. This assigns z the (symbolic) value y. It doesn't assign y any value. 4.8 Troubleshooting assignments 57 (4.18) (4.19)
(4.20)
To undo all assignments, use restart Sometimes you want Maple to Iorget all the assignments you have made in a session. You can get this to happen either by using unassign on each assigned name, or by entering restart in Math mode and then hitting enter. This will unassign everything,undoing all the assignments. restart does not erase the worksheet, however. The worksheet still looks the same, including the written record oI the assignments you had previously done. What the restart does is to delete all the slots you have set up in your mental model. Some names are already used by Maple. You will get an error message if you try to assign to them yourself. When you Iirst start up Maple, the names that you would ordinarily think oI using to assign to are not assigned. However a Iew are, such as the symbolic constants Pi and I. Maple will tell you that such names are reserved Ior system use. You need to pick another name. Table 4.9: Some Names can't be assigned to Example Commentary Error, attempting to assign to `Pi` which is protected
You can't redeIine a symbolic constant. Error, controlling variable oI Ior loop must be a name
for isn't a symbolic constant but it is used in Maple's programming language. So we can't use it as a variable. We can tell that something Iunny is going on because the Ior is automatically turned into a bold for, and a red box appears around the initial part oI what we typed. Error, attempting to assign to `solve` which is protected
solve is the name oI operation that solves equations. You can't change its meaning by using it as a variable to assign to. Can't solve for a variable with an assigned value The solve operation takes an equation, and solves with respect to a variable. II that variable becomes assigned a numeric value, then solving again won't work because evaluation causes Maple to see only the number, not the symbol being solved Ior. Problems occur with other Maple operations that need a named variable, such as plotting. 58 4 Chapter 4 Assignment Table 4.10: Can't solve for a variable with an assigned value (4.22) (4.23) (4.24)
(4.25)
At this point, right-clicking on the equation x`25*x60 won't reveal Solve as an operation that can be perIormed:
This is because the equation is evaluated beIore the right-click menu is activated, producing the equation 300. Since 300 has no variables, Solve isn't permitted since it makes no sense. II we do a restart and then enter the equation, we can solve it because x's assignment is gone. 4.9 Summary oI Chapter 4 material 59 (4.26) (4.27)
(4.28)
iI we assign x a value, then plotting the expression produces a straight line 30. This is because the expression is evaluated (producing the constant 30) beIore it is handed to the plot operation. Plotting a constant is what produces the straight line. 4.9Summary of Chapter 4 material Assignment General form Examples
Assignment is perIormed by using the assign to a name operation oI the clickable menu. (4.29) (4.30) 60 4 Chapter 4 Assignment Assignment also be perIormed by typing in the name, Iollowed by :, Iollowed by the expression whose value will be the result to be assigned.
svmbol name : expression
(4.31) (4.32)
Unassignment General Iorm Examples unassign(' svmbol name ) (4.33)
(4.34)
Undoes all assignments made by the user in the session so Iar.
The state of the Maple session The Variable Panel indicates the variables that are currently assigned in the Maple session, and their assigned values. 61 5Chapter 5 Building scripts 5.1Chapter Overview We brieIly discuss a Iew extra concepts useIul with solve: how to use a combination oI relations rather than just a single equation, and how to take apart or combine by the various Iorms oI solve. We then explore the concept oI script. a sequence oI operations useIul Ior solving a problem. Having a script makes it easy to solve diIIerent versions oI a problem by editing the parameter values and re-executing the script. OIten, the justiIication oI the eIIort to program a computation is driven by its reuse -- repeating the same computation with slight alterations each time. A Irequently recurring scenario is a parameteri:ed computation: 1) use variables to assign values to the parameters and 2) have subsequent steps oI the computation reIer to the parametric variables. Maple is well-equipped Ior reuse oI parameterized scripts, since it has an !!! button on the Maple menu that will execute in sequence all the operations in a worksheet. Re-execution can also be speciIied by Edit Execute Selection or Worksheet. 5.2Getting information from solve, data structures The result oI the solve operation can have multiple parts. When there are multiple solutions to the equation, the result oI solve is a sequence, list, or set oI solutions. We can select a part by giving an index (1 or 2, typically). Table 5.1: Selecting parts of a solution
We enter the equation, then right-click on it and select the solve item Irom the menu. This produces a sequence oI two solutions. We right-click on that and pick the Select Element menu item to get the submenu that allows us to pick the Iirst entry.Selecting the Iirst element oI the set gives us the equation. Selecting the right hand side oI the equation gives us the Iirst root.
II we give solve a linear equation, it has only one solution. We can still select the Iirst entry Irom the set, and then the right hand side oI that to get the root.
The right-click menu also oIIers the solve for variable item, which allows us to solve Ior x explicitly. The answer comes back in a slightly diIIerent Iorm, but it still has parts that we can select Irom. Maple (as well as many other programming languages) can compute with objects that have structure. Here are Iour diIIerent kinds oI structures that Maple can handle: Table 5.2: Basic data structures in Maple and operations to extract parts of them Type of structure What they look like Examples Equations, inequalities What math books do Ior equations and inequalities. The clickable menu allows you to get at the left hand side and right hand side oI an equation or inequality. (5.1) (5.2) 62 5 Chapter 5 Building scripts Type of structure What they look like Examples (5.3) (5.4) Sequences Values or expressions separated by a comma (5.5) (5.6) (5.7)
Sets A sequence surrounded by curly braces } (5.8) (5.9) Lists A sequence surrounded by square brackets | | (5.10) (5.11) Note that the result oI this solve is a set oI equations. For the time being, we just want you to recognize the diIIerent kinds oI structures that are output by solve and other Iunctions and be able to select parts Irom them. Later on we will get a lot oI work done by perIorming more sophisticated operations with them. 5.3Finding simultaneous solutions, constraining solutions. Suppose we want to solve the system oI equations and . This means Iinding values oI x and v that simultaneous satisIy both equations. We can do this in Maple by typing in the Iirst equation and then the second, separated by a comma. This is called entering a sequence oI equations. Right-clicking (control-click on Macintosh) on the sequence will allow you to solve the system. 5.4 Scripting: making computational work easy to reuse 63 In Lab 1, you discovered that solve could also handle inequalities as well as equalities. You can enter a sequence oI equations and inequalities to solve. This can be used to limit solutions to a particular range oI values. Table 5.3: Solving simultaneous equations (5.12) (5.13)
The result oI this solve is a set oI solutions. (5.14) (5.15)
We assign an equation to p, and solve it Solving this equation produces 4 roots. Two oI them are complex numbers (since they have I in them). The others are real. (5.16) (5.17) (5.18)
We enter a sequence consisting oI the equation named p, and the inequality . When ask Maple to Iind values oI x that satisIy both the equation and the inequality simultaneously -- roots oI the equation p that are non-negative. We might be interested in only non-negative real solutions, iI, Ior example, we were using the equation to model a physical situation and x was measuring weight. Negative values Ior weight wouldn't be a solution we'd be interested in. 5.4Scripting: making computational work easy to reuse Consider the problem you did in Lab 1, along with a solution: Version 1 and solution From Anton, Calculus, 8th edition, ch. 1 review exercises, problem 37, p. 99. A breeding group oI 20 bighorn sheep is released in a protected area in Colorado. It is expected that with careIul management the number oI sheep, , aIter years will be given by the Iormula: 64 5 Chapter 5 Building scripts and that the sheep population will be able to maintain itselI without Iurther supervision once the population reaches a size oI 80. (a) Graph versus . (b) How many years must the state oI Colorado maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .) Solution to (a) We can enter the equation Irom the problem, but we really need the right hand side oI it because the plot operation can't plot equations, it can only plot things that evaluate to a number (rather than an equation). Once we have the expression Ior the sheep population, we need to play with the plotting ranges to see when the leveling oII occurs. We'd have to think about it and experiment a bit -- but the computer makes the replotting easy to do once we make our decisions about what to try. (5.19) 5.4 Scripting: making computational work easy to reuse 65 Solution to (b) (5.20) (5.21) We can read the leveling oII point Irom the plot, assuming that we have Iigured out the appropriate time range in (b). Alternatively, we can do a little calculus and take the limit oI the expression as t goes to inIinity. (5.22) We can imagine ourselves working as a environmental engineer Ior the National Forest Service and being very pleased with ourselves Ior solving the problem with Maple. But now we are handed two more wildliIe management problems to do, Irom other regions in our territory: Version 2
A breeding group oI 33 bighorn sheep is released in a protected area in Colorado. It is expected that with careIul management the number oI sheep, , aIter years will be given by the Iormula:
and that the sheep population will be able to maintain itselI without Iurther supervision once the population reaches a size oI 85. (a) Graph versus . (b) How many years must the state oI Colorado maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .)
Version 3
A breeding group oI 45 bighorn sheep is released in a protected area in Colorado. It is expected that with careIul management the number oI sheep, , aIter years will be given by the Iormula: 66 5 Chapter 5 Building scripts
and that the sheep population will be able to maintain itselI without Iurther supervision once the population reaches a size oI 90. (a) Graph versus . (b) How many years must the state oI Montana maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .)
We have the Ieeling that we will shortly be handed problems Ior a number oI other locations as well. How can we reuse our original work with minimal eIIort? II we had the Iirst solution, we could produce the second solution through copv-paste-edit-re-execute. Table 5.4: Executing a clone of a script through copy-paste 1. Copy and paste the original solution into a new document, or to a spot later in the same document. You do this as with a word processor -- select a region oI the worksheet with the mouse, type control-C (command-C on a Mac). Then position the document cursor in the destination, and type control-V (command-V on a Mac). A duplicate oI the solution should appear there. 2, Using the mouse, edit the Iormulae as needed. You only need to edit the black (input) Iormulae, not the blue ones. 3. Position the mouse at the Iirst computation and hit enter. Continue to work your way through the sequence oI the commands. 4. Alternatively, select the entire region containing the edited version oI the solution and hit Edit-~Execute-~Selection. 5. II the region to be executed is the entire worksheet, then you can hit the !!! button oI the Maple toolbar, or you can do Edit ExecuteWorksheet. The results oI executing the edited script are not totally correct. We will have to change a Iew things by hand: the clickable operation "evaluate at a point" in step (b) will use N80 (which is what the copy says) instead oI N85, so we will have to redo it. Also, the last plot will not show an appropriate vertical range unless we do that. We'd like to do a little less oI this hand-tuning in re-execution. Also, we'd like to make it easier to remember what to change between multiple versions. To see the edited version oI the script look at A breeding group (page 68). 5.5Rewriting the script by assigning parameters at the start of the script While copying and editing is probably a little Iaster than typing in the whole script again, we would also spend time hunt around Ior assignments to edit each time we wanted to re-run the script. We can reduce the "hunting around" by adopting the Iollowing working rule: identiIy the parameters oI the problem, and change the script so that it assigns values to all parameters at the beginning oI the problem. This does not mean "put all assignments at the beginning oI your script". Only the assignments involving parameters -- values that are speciIied by the problem description -- need to be relocated to the start oI the script. 5.6 Summary oI script writing 67 Finding and naming parameters First, solve at least one version oI the problem. Then, imagine what would need to be changed iI you were trying to solve alternative versions oI the problem. You can Iind parameters iI you have several versions oI a problem by looking at what changes in the worksheet Irom version to version. For example, in the sheep problem, we note the Iollowing things changing in diIIerent versions oI the problem.. We pick names Ior these. 1. the numerator oI the "sheep equation" (P) 2. the coeIIicient in the denominator oI the equation (c) 3. the value oI the stable population (s) The other number in the script is the original population oI the sheep. We realize that it can be derived by evaluating the "sheep equation" at t0. Thus this value does not need to be a parameter as we can derive it Irom the other inIormation. It might be a good check though. We then write the script to assign values to the parameters at the start oI the script, and then write the other operations and expressions in terms oI the symbols. This allows us to redo the script just by changing the values at the beginning oI the script. We use the word processing Ieatures to add extra directions to make the script easier to use, basically saying "here, change these things", and "this is the end oI where you should stop copying". To see the edited version oI the script look at Attachment. Jersion 2 of Sheep Script, with parameters (page 70). Having created this script, we can handle the third version oI the problem by editing the values oI the parameters and executing the script again by selecting the entire script with the mouse, and then doing Edit-~Execute-~Selection. We get this result: 5.6Summary of script writing Script writing is appropriate when vou expect to handle several different versions of the same problem. In proIessional work, this is oIten the case -- iI it's worth doing at all, it's probably going to occur more than once. Figure out how to solve the problem first. Then write the script. There's really not much point in writing the script iI you don't have some idea oI the sequence oI operations in it. Once you have a worksheet oI instructions Ior solving one version oI the problem, look at it and the other versions and find the parameters. Set up a new worksheet where the Iirst thing you do is to assign values to the parameters. Then work through the rest oI the instructions and rewrite them to use the parameters instead of the fixed values from one version of the problem. 5.7Troubleshooting scripts Programming books have the tendency to show things that work. They say less about what to do about the things that don't work. However, it is usually the case that computer users oIten spend more time "getting things to work" than "working". Learning how to get out oI jams is at least as valuable as knowing how to enter operations and what they mean. We oIIer this advice, which is "commonsense about work" as applied to interactive soItware development: 1. Solve one version oI the problem beIore you try to start scripting. You can use Maple to experiment -- enter and edit snippets oI operations that try out the solution technique Ior part oI the problem. Eventually edit them together so that they solve the whole problem. II you have only Iuzzy notions about the math or the operations you want to proceed, your computer work will just ampliIy that. Having a worksheet that solves one version oI the problem can remove a lot oI the Iuzziness. Where does the inspiration Ior solving the problem come Irom? II you are lucky, the solution may be told to you. Or you may Iind a description oI a similar problem as a starter. But the big bucks, as they say, go to those who can devise the solution plan themselves. 2. Limit each step so that it is a small step. II you get into trouble, you will be able to nip it at the bud. This becomes a more prominent tactic in later work when we are tempted to construct long-winded one-line expressions that do everything at once. 68 5 Chapter 5 Building scripts 3. Test pieces individually, then put them together. For example, iI you don't really understand how to make a dotted line plot in teal with a title, you should try to do that with a simple plot (such as ) rather than an expression whose shape you aren't that Iamiliar with it. Then take what works and substitute the real expression you want to plot in a copy oI the plot operation. The complexity oI troubleshooting is reduced iI you have Iewer lines oI untrustworthy code to look through Ior problems. This can be called divide and conquer troubleshooting. 4. II what you have doesn't work, Iind something similar which does work, and then incrementally edit it. For example, iI you can't get in, then Iirst see whether you can get to work. Once you succeed with that, edit the expression to and so Iorth. 5. II strange things continue to happen despite your best eIIorts to troubleshoot, it may be that previous settings in the Maple session are interIering with your current work. Recall that some people in the ENGR101 lab couldn't get their oscilloscopes to work because oI settings changed in the oscilloscopes by groups earlier in the day. This can be particularly true iI you are developing scripts and are assigning parameter values, then switch to development oI another script in the same document. The values you assigned will not magically unassign themselves when you start working on something new in the same worksheet. The remedy Ior this is to put a restart in as the Iirst operation in your script, then re-execute the worksheet. 5.8Attachments Attachment: Version 2 of sheep script without parameters Version 2 of sheep problem, with edited script A breeding group oI 30 bighorn sheep is released in a protected area in Colorado. It is expected that with careIul management the number oI sheep, , aIter years will be given by the Iormula: and that the sheep population will be able to maintain itselI without Iurther supervision once the population reaches a size oI 85. (a) Graph versus . (b) How many years must the state oI Colorado maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .) Solution to (a) 5.8 Attachments 69 (5.24) Solution to (b) (5.25) (5.26) We can read the leveling oII point Irom the plot, assuming that we have Iigured out the appropriate time range in (b). Alternatively, we can do a little calculus and take the limit oI the expression as t goes to inIinity. (5.27) 70 5 Chapter 5 Building scripts Attachment: Version 2 of Sheep Script, with parameters Version 2, with use of parameters Start of parameters -- change these for each version of the problem (5.28) (5.29) We call the size oI the stable population s. (5.30) End of parameters (a) Graph versus . (b) How many years must the state oI Colorado maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .) (a) (5.31) Note that sheepPopExpr is not a parameter since assignment is always the same Ior all versions oI the problem. To make the graphing work all the time, we set the vertical axis to "P30" rather than a Iixed value. This will set the vertical axis so that it will be 30 more than the value oI P which Irom the Iirst problem we have realized is the top oI the graph. (5.32) 5.8 Attachments 71 (5.33) This is the time in years that model predicts it will take Ior the sheep population to reach selI-sustaining status, allowing the wildliIe managers to move onto another job. (c) A little thinking reveals that the leveling oII value (as indicated Irom the graph), is the numerator oI sheepPopExpr, since the denominator goes to 1 as t goes to inIinity. (5.34) 72 5 Chapter 5 Building scripts End of script Attachment: Version 3 of Sheep Script, with parameters Start of parameters -- change these for each version of the problem (5.35) (5.36) (5.37) We call the size oI the stable population s. (5.38) End of parameters (a) Graph versus . (b) How many years must the state oI Colorado maintain a program to care Ior the sheep? Show your work. (c) How many bighorn sheep can the environment in the protected area support? (hint: examine the graph Ior large values oI .) (a) (5.39) Note that sheepPopExpr is not a parameter since assignment is always the same Ior all versions oI the problem. To make the graphing work all the time, we set the vertical axis to "P30" rather than a Iixed value. This will set the vertical axis so that it will be 30 more than the value oI P which Irom the Iirst problem we have realized is the top oI the graph. (5.40) 5.9 Summary oI Chapter 5 material 73 (5.41) This is the time in years that model predicts it will take Ior the sheep population to reach selI-sustaining status, allowing the wildliIe managers to move onto another job. (c) A little thinking reveals that the leveling oII value (as indicated Irom the graph), is the numerator oI sheepPopExpr, since the denominator goes to 1 as t goes to inIinity. (5.42) End of script 5.9Summary of Chapter 5 material Type of structure What they look like Examples Basic data structures in Maple 74 5 Chapter 5 Building scripts Type of structure What they look like Examples Equations and inequalities Expression related by , ~, , , , or . (5.43) (5.44) Sequences Values separated by a comma (5.45)
Lists A sequence surrounded by square brackets | | (5.46)
Sets
A sequence surrounded by curly braces } (5.47)
Solving simultaneous equations (5.48) (5.49)
The result oI this solve is a set oI solutions. (5.50) (5.51)
Solving this equation produces 4 roots. Two oI them are complex numbers (since they have I in them) the others are real. (5.52) This gets the solver to list only the positive real solutions. We might be interested in only non-negative real solutions, iI, Ior example, we were using the equation to model a physical 5.9 Summary oI Chapter 5 material 75 (5.53) (5.54)
situation and x was measuring weight. In this case the other values oI x wouldn't be relevant to our situation. Scripts Creating a script Ior a problem In a Maple worksheet, take a version oI a problem and create a sequence oI operations in the worksheet that solve it.
Note similarities and diIIerences between diIIerent versions oI the problem. Envision what you'd have to change in the worksheet in order to solve a diIIerent version oI the problem, and what would stay the same. You may have to rewrite some oI the expressions to reIer to the parameter rather than the value.
Assign the parameters at the beginning oI the script. Rework the rest oI the script so that the Iormulas reIer to the parameters by name, rather than the values used in the original version oI the problem.
For example, iI the value 42 appears in several places in your script, deIine a parameter p : 42 at the start oI the script and edit the other occurrences oI 42 to be p instead. When you have a diIIerent version oI the problem, you can edit just the single line p : 42 into say p : 47 and won't need to edit any other lines oI the script.
Using a script Copy and paste the script to a new location.
Edit the assignments to reIlect the new version oI the problem.
Click on the !!! button oI the Maple toolbar to execute the entire worksheet. Or select a portion oI it with a mouse and hit Edit-~Execute-~Selection. As a last resort, just hit enter (return on Macintosh) multiple times to perIorm the operations in the new version oI the script. Rationale Ior using scripts More work to do than clickable interIace the Iirst time. Saves time iI you expect to want to reuse the operations on multiple versions oI the same problem. Also it is less error prone. Divide and conquer troubleshooting Test each piece oI the script as soon as soon as you build it, rather than waiting to test it only aIter you have entered it all. It's easier to test incrementally, a piece at a time, because iI there are Iewer lines oI code to suspect oI causing problems. 76 5 Chapter 5 Building scripts 77 6Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation 6.1Chapter Overview We introduce textual entry oI solve and plot operations, where the operation is speciIied by keyboard alone, without the use oI the mouse or palettes. Textual entry is oIten preIerred by programmers because it is easier to edit scripts written with text. We will retain use oI the clickable interIace Ior doing quick one-time calculations, or Ior developing ideas the Iirst time beIore we start script-writing. We being to introduce additional concepts in Maple, to enhance what we can solve and plot: 1. In Maple, a character string is a collection oI characters delimited by "s: "This is a string." We see how strings are used in the textual entry oI labels and colors in plots. 2. We discuss lists e.g. [1,2, x, 3.5]. We Iirst saw them in Getting information from solve, data structures (page 61) provide a way oI organizing multiple results in a single "data container", making it to operate on the whole collection oI results while retaining the ability to getting at individual results Irom within the collection. Lists are used in both solve and plot. 3. solve uses two other types oI data containers: sequences and sets. We describe how to recognize them. and how to extract inIormation Irom them. 4. Programmers rely on the on-line documentation to manage the complexity oI remembering the details oI a knowledge-intensive system such as Maple. They learn/remember how to use a Ieature by looking up the description, Iinding an example close to what is desired, and then actively experiment with the example in a Iresh worksheet. Reading without experimentation is usually not very productive. 5. In Chapter 4 Assignment (page 45), we explained assignment and how Maple uses assigned values whenever it sees a name in an expression. We introduce the eval operation, which allows variables to take on values during evaluation without assignment. Another way to view eval is that it is a way Ior assignments to be done temporarily and immediately Iorgotten. This can be an attractive alternative iI you are concerned about situations where you'd be making many assignments and then undoing them through unassign. eval allows you to evaluate an expression Ior a particular value oI a variable in one line, rather than having to type in the assignment and unassignment as well. 6.2Textual entry of operations The textual Iorm oI an operation in Maple has the general Iorm: operationName ( sequence of values ) The operationName can be something like solve or plot. By sequence of values, we mean one or more items, each item separated Irom the next by a comma. "Sequence" here is the same kind oI sequence that was Iirst seen in the previous section on solve (page 62). Maple will evaluate what vou enter in the same way that was described Ior mathematical expressions possible (page 41). II there are assigned variables mentioned in the sequence, then their values will be used. II Maple knows the operationName (e.g. sin, solve, plot), then it will perIorm the calculation speciIied by the built-in programming. Otherwise, the result will be more or less what you typed in. The technical term Ior the "values" in this situation is actual parameter or argument. Note that the parentheses around the sequence oI values are mandatorv -- you will either get an error or a result that's Iar Irom what you want iI you omit the parentheses. This style oI writing things is sometimes called functional notation. In mathematics examples oI Iunctional notation are f(x) or g(3,5) . In these examples, the name oI the operation is the Iunction name f or g, while the actual parameters or arguments would be x or the sequence 3,5. Evaluating the function is what causes Maple to perform the action. Table 6.1: The textual form of equation solver solve The Iorm oI the answer returned by the textual version is slightly diIIerent Irom invoking solve through the clickable 78 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation (6.1)
interIace. The Iormer is typically a Iorm that is easier to work with in scripts.
In this, the operation Name (or Iunction name) is solve. There are two arguments. The Iirst argument is the equation . The second argument is the symbol x. In this situation the result oI perIorming the solve operation is a sequence oI two numbers, the two roots oI the equation.
(6.2)
What you get iI you leave out the parentheses -- not much! Because you leIt out the parentheses, Maple does not think you are asking Ior any Iunction to be evaluated, which is how the work gets done.
Error, unable to match delimiters
You get another one oI those "unable to match delimiters" messages iI you Iorget one oI the parentheses.
Error, invalid power
This is what happens iI we Iorget to use the right arrow key to descend Irom the exponent oI . Maple thinks that we are talking about x to a power called 2-2,x, which understandably it doesn't make sense to it as a power. 6.2 Textual entry oI operations 79 Table 6.2: The textual version of plotting
This is a textual Iorm oI plot. The Iirst argument is an expression, the second argument is an equation naming a variable and a range oI a plot. Note that iI we wanted to change the range Irom -3..3 to -5..2 then we would just edit that line oI the worksheet and hit enter again. II we wanted to redo the plot in the clickable interIace, we would have to right-click and enter all the inIormation all over again.
II the second argument is just the variable, then plot uses deIault values Ior the range. 80 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation (6.5)
No plotting happens iI we Iorget the mandatory parentheses.
Suppose we entered this instead oI . There is no error message, but the picture is not like the Iirst plot. Why did we get something diIIerent?
The only way that we would discover that a mistake is iI we already had an idea oI what the graph should look like, and noticed that the result diIIered signiIicantly Irom what we expected. II you haven't Iormed a basis Ior expectations, you won't discover such mistakes. Once you realize that the picture is incorrect, you would be spurred to search Ior the cause. Since there are no error messages and a plot (albeit a weird one) was produced, the most likely cause is that the arguments to the plot Iunction are wrong. The obvious place to look Ior correct examples is the on-line documentation II you look at the on-line documentation Ior help, you will see that giving plot three arguments means something diIIerent -- the third argument can be taken as the value oI the vertical range oI a plot. Evidently what is happening is that you are seeing only the tiniest top slice oI the plot produced above because oI the inadvertent speciIication oI the vertical range.
This example illustrates the Iact that just because there is no error message, it does not mean that all is correct. The computer needs to be told what to do in a way that it can Iollow. The rules are typically more restrictive than those oI ordinary human language. An attachment at the end oI the chapter shows the textual Iorm oI common Iunctions, subscripts. These textual Iorms can be entered Irom the keyboard wherever the palette entry would work. 6.3Why are there two different styles for entering operations7 The clickable interIace is a good way to get a calculation done quickly, but the actions speciIied in this way are hard to edit when building scripts. Maple, like most languages, has a textual version oI all operations it perIorms. The editing involved in scripting development can oIten be easier 6.4 Plotting a list oI expressions (multi-plots), plotting lists oI numbers (point plots) 81 to do on the textual version. In other words, the clickable interface is good for a one-time calculation, but not so good for the editing and re- execution involved in script reuse. Another advantage oI the textual mode oI operation is that the number and variety oI operations available in textual Iorm is Iar greater than what's available in the clickable interIace. Maple has several thousand operations. Building a clickable interIace to all oI them would result in tedious navigation through menus that would either be huge or involve many sublevels. The downside oI using the textual entry is that the developer must spell the text correctlv, with the right number and placement of parentheses. Experienced users Iind that the textual interIace is Iaster to deal with Ior scripting, while the clickable interIace is Iaster Ior short, more casual use. Fortunately, in either case one can edit Iailed attempts and retry, so perIect entry is not necessary to be productive. Becoming proIicient with textual entry oI operations is part oI the transition technical users make in going Irom reuse oI other's work to routinely creating their own programming. Without such proIiciency, it is hard to realize the Iull power oI the computer in modeling and simulation situations. 6.4Plotting a list of expressions (multi-plots), plotting lists of numbers (point plots) Recall that lists in Maple are a way oI collecting expressions together into a single object, as discussed in the previous table describing lists and other data containers (page 62). You speciIy a list by listing the items in the list , enclosed in square brackets | |. II the Iirst argument to plot is a list oI expressions, then plot will on a single graph display the plots oI all the expressions in the collection. By deIault, each one will be displayed in a diIIerent color. Table 6.3: Plotting of multiple expressions Example
Plot two expressions on a range where both have comparable-sized results. We use the list to indicate the two expressions that should be plotted.
82 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation Example
Problem: approximately where is the expression equal to 5? While we could use solve to tell us exactly, it's oIten worthwhile to draw a picture and process the situation visually. II we give plot the two expressions "-5" and then plot will plot not only the parabola (the second expression, it will also plot the expression that is always -5 Ior any value oI x. This corresponds to the horizontal line drawn on the plot. Visually we can see that the parabola is -5 at roughly -.8 and 1.2. We can even get a little more precise by clicking on the plot and using the coordinate window as was discussed in Plotting, approximate numerical solutions through cursor position (page 25). 6.4 Plotting a list oI expressions (multi-plots), plotting lists oI numbers (point plots) 83 Plotting multiple expressions simultaneously can be useIul when you want to compare them. Assuming that the scales are comparable, one can get a sense oI similarity or dissimilarity "at a glance". We can plot data points rather than smooth curves, iI we give the textual Iorm oI plot separate lists oI x and v coordinates. can be used with the textual version oI plot . II we give the textual version oI the plot operation two lists oI numbers that have the same length, then plot will regard the Iirst list as a list oI x-coordinates, and the second list as corresponding v-coordinates. II you provide plot with the third argument stvlepoint, then it will produce a point plot. Otherwise, it will draw lines connecting each point. Table 6.4: Plotting points with lists of numbers (6.6) (6.7)
We use the textual Iorm oI plot to plot the points (1,5), (2,6), (3,7) and (4,-1).
84 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation
Without the third argument, plot will try to connect the points with a curve. Error, (in plot) unexpected option: Style point
Maple cares about whether things are capitalized or not. Stvle is not the same as stvle. 6.5Character Strings and putting titles and labels into plots A string in Maple is something enclosed in double-quotes: "red", "this is a string?", "GregoryBrothers4" are all strings. The double-quote symbol is mandatory Ior a string. Single-quotes ' (also known as apostrophes), backquotes ` (also known as acute accent marks) are not substitutes Ior double-quotes in writing Maple strings. Characters enclosed by apostrophes or backquotes mean something diIIerent to Maple. Use oI the wrong punctuation marks will lead to undesired results or error messages. In addition to being used to input data points in plot, lists also can be used in speciIying colors and axis labels. 6.5 Character Strings and putting titles and labels into plots 85 Table 6.5: Plot options and labels
II one oI the arguments to the plot operation is oI the Iorm then those colors will be used. Most reasonable names will work, but the Iull list can be seen in on line help (search Ior colornames). Note that we are using the textual version oI the symbolic constant a. II you can remember how to spell it, it can be easier than selecting it Irom the Common Symbols Palette.
Note that because the expressions being plotted are given in a set, the color assignment is not in the same order that they were typed in. II we wanted the same order, we should give the plot expressions in a list.
Error, unable to match delimiters Forgetting brackets Ior the list oI colors. Error, invalid interval
One oI the proIiciency issues with textual input is that you have to remember all the ( ) parentheses and | | brackets. Can you Iind the the missing delimiter(s)? 86 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation Error, (in sin) expecting 1 argument, got 2
II you leave enough delimiters out, you get error messages that don't complain about missing delimiters. You have to Iigure out what the problem is, which might involve a missing parentheses even iI the message doesn't say so. The "Error, (in sin)" is a cue that you should look at the places where you included sin in your text and inspect it Ior problems. It doesn't take too much eIIort Ior you to notice that there's no Iinishing parentheses in the Iirst sin(x . One reason why there was no error message about delimiters is that there are multiple missing parentheses. Because there are equal numbers oI missing leIt and right parentheses, there was no alarm Ior missing delimiters. Error, (in plot) expecting a real constant as range endpoint but received -4*pi
The problem with this plot is that pi doesn't mean the same thing to Maple as Pi. Maple is case-sensitive. Only Pi means the symbolic math constant having to do with the circumIerence oI a circle. II one oI the arguments to the plot operation is oI the Iorm then those will be used. Each title needs to be a string. In subsequent work, we will see strings used in other situations within Maple other than Ior plot titles. 6.6 Troubleshooting with strings 87 6.6Troubleshooting with strings The most common mistakes with strings is to leave out the delimiting "s, or to use the wrong kind oI delimiters. While the similar-looking keyboard characters ' (single quote or apostrophe), and ` (acute accent or backquote) look like would be equivalent, they are use Ior other purposes in Maple. Table 6.6: What happens when you forget to use the " delimiter in strong, or use the wrong character for the delimiter Error, invalid in
Forgetting to include "s around one oI the titles gives a cryptic error message about an "invalid in". II you were an experienced Maple user, you'd know that in is part oI the Maple programming language, but including "in" within a string would never be Ilagged as an error. This would be a clue that there's something wrong around where you entered the Iirst label.
The message is not very helpIul about telling you how to Iix the mistake, though. This unIortunately is typical in most computer programming languages, despite several decades' eIIort in building systems soItware to help people program. Error, invalid in
Putting the wrong kind oI quote -- ' instead oI " didn't make a string. We got the same indication oI a problem as beIore even though the problem is "wrong kind oI quote" rather than "no quote". 6.7Learning through on-line documentation and experimentation All the options available in the Plot Builder available through the right-click (control-click) interIace are also available in the textual version oI plot. In Iact, there are many additional options and varieties oI plotting available. The way to Iind out what the Ieatures are and how to invoke them is to consult the on-line documentation. 88 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation We can Iind out more about the textual Iorms oI plotting by invoking Help -~ Maple Help and typing plot into the search Iield. When we do so, we see the inIormation in the Iigure below: Table 6.7: Plot command help 6.7 Learning through on-line documentation and experimentation 89 We scroll to the bottom oI the page and Iind an example oI this. We are looking Ior a version oI plots where v1 and v2 are lists. We don't see something exactly like that but we do see something with Vectors which are similar. Since the document says this should work Ior lists or vectors, we take the example and see iI we can modiIy it Ior our own purposes: Table 6.8: Examples of plot Evidently, the the Iirst list is the values oI the x (horizontal) coordinates, and the second list the values oI the v (vertical) coordinate. We copy and paste the example into a Maple worksheet and then see iI we can get it to work. 90 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation Table 6.9: Copying the example According to the documentation, we should be able to get this to work iI the Iirst two arguments are lists or vectors. So we edit the example to do lists instead and re-execute the line to see iI it works in the same way. 6.7 Learning through on-line documentation and experimentation 91 Table 6.10: Modifying the example To learn about plot options such as colors and labels, we click on the plot,options item under the search results Ior plot (see green oval in the Iigure). Clicking on that item produces this inIormation. We see inIormation about color (with another link to see colors), along with possibilities, Ior labels, symbols, styles, etc. Again, the way to learn the options is through copying and pasting the examples into a Iresh worksheet, getting them to work, and then modiIying them to suit your own purposes. Table 6.11: Plot option help page
92 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation Note the "colour" -- this is a Canadian product. You will see things like this as well as other indications that it's not an all- American world out there. For example, you can convert pints into Imperial Gallons through Tools -~ Assistants -~ Units Calculator. 6.8More operations on lists So Iar we have talked only about creating lists, and assigning lists as the value of a variable. You can also generate a sublist of a list, find a particular item in a list bv its position index, count the number of items in the list, and convert a list into other types oI data. Table 6.12: Operations on lists Operation Example Commentary Create a list (6.12) (6.13)
Lists can contain symbols, numbers, expressions -- anything, even other lists.
6.9 solve, lists and sequences 93 Operation Example Commentary SpeciIy a sublist oI values (6.14)
II a list is Iollowed by another pair oI braces with a range inside, then a sublist is computed as a result. Here we have the list that's the Iirst through third items oI s1. SpeciIy one item Irom the list (6.15)
SpeciIy the last item in the list (6.16)
SpeciIy a sublist with one item (6.17)
SpeciIy a sublist Irom the 3rd Irom the end to the end (6.18)
Count the number oI items in the list (6.19)
Add together all the items in the list (6.20)
Compute the average oI all the numbers in the list. (6.21)
Convert a list into a sequence (6.22) op has an idiosyncratic name Ior an operation. It stands Ior "operands". Convert a list into a string. (6.23)
6.9solve, lists and sequences To solve a system oI equations, use a list oI expressions or equations Ior the Iirst argument to solve. Use a list oI variables as the second argument. solve will return a sequence oI lists as the result. When solve Iinds two solutions Ior an equation (such as iI the equation is quadratic), it will return a sequence oI solutions. You can recognize a sequence and distinguish it Irom a list because, the sequence is missing the enclosing brackets| | that a list has. Part-selection operations work in sequences in a similar Iashion as they were described here (page 92). 94 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation In solve, lists and sequences look as iI they are almost interchangable. Later on we will see situations where lists and sequences must be handled diIIerently. Table 6.13: Solving systems of equations with solve (6.24) (6.25)
We get a sequence oI solutions since there is a double root.
(6.26) We evaluate the equation at the Iirst root and see that it does satisIy the equation. (6.27) Same Ior the second. Error, attempting to assign to `system` which is protected
We want to assign a set as the value oI the variable system. Maple tells us that the name is already in use as a built-in Iunction, so it won't let us do that.
(6.28)
We choose a diIIerent variable to assign the set to. (6.29)
(6.30)
We speciIy the set oI variables we want to solve Ior, then call solve. We get a list with one element (which itselI is a list) as a solution. 6.9 solve, lists and sequences 95 (6.31) We extract the Iirst element oI the list. Notice that that are Iewer | |s. (6.32) We evaluate the system at the solution that solve has Iound and veriIy that this really does satisIy the system oI equations. (6.33) (6.34) This system oI equations has two distinct solutions, so we get a list with two elements in it. Each element is a distinct solution. (6.35) (6.36) (6.37)
(6.38) (6.39) (6.40)
We can Iind the non-negative roots oI an equation by including the appropriate inequality in the list oI relations given to solve. The result by deIault is a set. however, iI the second argument to solve is a list oI variables, then the result will come back as a list. You can select items Irom a set using the same notation as with lists. 96 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation 6.10Evaluation, eval, and assignment Here's a problem to consider: We have an expression relating time t to voltage registered by a capacitor as it is being charged by a battery. In a mathematics or electrical engineering textbook, we might see this written as . We are interested in taking this expression Ior voltage and doing several calculations with it -- plotting it Ior a range oI t, Iinding values oI t that correspond to a speciIied voltage (e.g. "Iind the time t when the voltage reached 55 volts"), or Iinding a voltage corresponding to a speciIied time (e.g. "Iind the voltage at t2.5 minutes aIter the start"). II we set up an assignment in Maple ,, then we could calculate the voltage at t2.5 minutes by assigning t the value 2.5 and then evaluating V. The second evaluation will cause the current value oI t to be used. However, iI we wanted to plot the expression J aIter that, then we'd have problems because whenever we would type t, Maple would use the value oI t rather than the svmbol t. Table 6.14: Evaluating an expression using a particular value of one of the variables in the expression, and then plotting (6.41) (6.42) (6.43)
Error, (in plot) unexpected option: 2.5 0 .. 10
Rather than t0..10 Maple is seeing 2.50..10 because it is using the value oI t when evaluating what we typed. We can clear the path Ior plotting by unassigning t Iirst. Note that iI we did a restart instead oI an unassign we would lose the assignment to J. restarting at this point is a bad idea, since it Iorces us to redeIine V as well as t. 6.10 Evaluation, eval, and assignment 97
The same problem would happen iI we tried to solve an equation involving V iI we had already assigned t a value. Table 6.15: Evaluating an expression using a particular value of one of the variables in the expression, and then solving (6.44) (6.45)
We set up an expression and then evaluate it at t4.7 seconds Warning, solving Ior expressions other than names or Iunctions is not recommended. Error, (in solve) a constant is invalid as a variable, 4.7
Because Maple is evaluating the names V and t in the solve operation, it is seeing which it cannot solve because there are no variables in the equation to solve Ior. We can clear the path Ior solving by unassigning t Iirst. Doing a restart would not work, because that would also unassign 98 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation (6.47)
everything, including V. We would lose the expression we want to solve Ior. It can be tedious to have to remember to unassign variables iI we want to go back to using them as symbols in the expression. We recommend using the eval operation (also available in the clickable menu as ) instead oI assignment, iI you are switching back and Iorth between using values Ior a variable and using it as a symbol. eval returns the same result as iI you had done assignment temporarily, but there is nothing to be undone aIterwards. You can evaluate using values Ior several variables by giving a list oI equations instead oI a single equation as the second argument to eval. Table 6.16: Evaluating an expression using a particular value of one of the variables in the expression using eval, and then solving (6.48) (6.49)
We set up an expression and then evaluate it at t4.7 seconds. (6.50)
Evaluating V produces the same result as beIore (an expression with the symbol t in it), so we can immediately set up an equation and solve it Ior t.
(6.51) Note that the eval did not assign a value to t. It's still just a symbol at this point. Begin parameters (6.52) (6.53) This is an example oI how to set up a script using parameters while taking advantage oI eval. Several symbols in the expression Ior voltage are set up and assigned as parameters. The expression that describes how voltage changes over time is not a parameter, although it is assigned a name Ior easier use in subsequent steps oI the computation.
6.10 Evaluation, eval, and assignment 99 (6.54) (6.55) End parameters (6.56)
(6.57) (6.58) (6.59) (6.60) Table 6.17: An example using assignment and eval Begin parameters (6.61) (6.62) This is an example oI how to set up a script using parameters while taking advantage oI eval. Several symbols in the expression Ior voltage are set up and assigned as parameters. But we use eval to maintain and t as symbols in the expression Jprime. 100 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation (6.63) (6.64) End parameters (6.65)
(6.66) (6.67)
We use the inIormation that the capacitor is observed to at vt volts at time tt0 to Iind the value oI that is consistent with this. (6.68)
(6.69) tExpr is the value oI the expression with the values oI the parameters and the calculated value oI plugged into Jprime. We can solve an equation based on this Iormula to Iind the time when we achieve a voltage oI 55 volts in this conIiguration. 6.11 Summary oI Chapter 6 material 101 6.11Summary of Chapter 6 material Troubleshooting textual input in Maple Remember to... Examples with error(s) Supply a Iunction name and arguments (parameters) should be Match delimiters (parenthesis and brackets) should be Press the right arrow key to exit Irom variable exponents should be Set ranges correctly when plotting should be Examples Plotting multiple expressions Plotting with lists (6.70) (6.71) Using multiple colors in a multi-plot Set the titles oI the axes Using Maple's built-in help Use Help~Maple Help or press Ctrl-F1 (Command-F1 on a Mac) Remember that you can click on related topics when viewing the help Ior a particular command Operations on lists Examples Create a list (6.72)
102 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation SpeciIy a sublist oI values (6.73) SpeciIy one item Irom the list (6.74) SpeciIy a sublist with one item (6.75) Count the number oI items in the list (6.76) Add together all the items in the list (6.77) Compute the average oI all the numbers in the list. (6.78) Convert a list into a sequence
Convert a list into a string (6.79)
(6.80) Solving a system of equations using lists Examples Create the system oI equations (6.81)
Set the variables oI the system (6.82)
Solve the system and extract the Iirst solution oI possibly many solutions (6.83) Evaluating an expression with eval instead of assignment Examples 6.11 Summary oI Chapter 6 material 103 eval allows you to substitute a value Ior a variable within an expression, without assigning that value to the variable. (6.84) (6.85) (6.86)
104 6 Chapter 6 More sophisticated scripting: textual entry, multiplots, point plots, character strings, lists, solving equations, and evaluation 105 7Chapter 7 Using and Defining Functions 7.1Chapter overview Functions occur so much in mathematics that it's natural that Maple knows a lot about them and how to compute with them. You can also deIine your own Iunctions in Maple, as with most other programming languages. There are a Iew pitIalls in the use oI Iunctions in Maple: a) The names oI common mathematical Iunctions used in Maple may diIIer Irom what you are used to Irom high school math. b) Some Iunctions in Maple do non-mathematical things, such as solve, and plot. Others take novel arguments -- lists, equations, and ranges, rather than numbers. c) Maple Iunction deIinition uses : and -~ rather than equals () as Iound in conventional math textbook notation. This is because the "context- Iree" language processing oI Maple thinks an equation is being deIined whenever it sees an equal sign. It's currently inIeasible Ior conventional programming language-processing technology to use context. 7.2Functions in computer languages: a way of producing an output from inputs Everyone is introduced to the idea oI a function in secondary school mathematics: Calculators can compute many oI the common Iunctions Iound in high school algebra and pre-calculus: sin, cos, ln, , etc. Maple can evaluate these Iunctions. The common ones are Iound in the Expression palette but there are hundreds more. When entering a Iunctional expression, the syntax used is: function name ( sequence of arguments ) The parentheses are mandatorv in Maple. Forgetting parentheses can be irksome because oIten the computer leaves you to Iigure out yourselI that the answer you're getting is wrong. Table 7.1: Function results in Maple Example Commentary (7.1) When we enter a sequence oI Iunctional expressions, we get a sequence oI results that come Irom evaluating the expressions. All the common Iunctions know how to give limited-precision results given limited precision inputs. (7.2) Maple's programming will return an exact number iI the Iunction has that kind oI result Ior the given input. However, iI a simple exact result can't be Iound, Maple will return what you typed in. Sometimes there is a little simpliIication that goes on so what comes out is not literally what comes in, although it usually obvious that it is mathematically equivalent. For example, Maple will always simpliIy Iractions by eliminating the greatest common divisor Irom the numerator and denominator. 106 7 Chapter 7 Using and DeIining Functions Example Commentary Error, invalid input: cos expects its 1st argument, x, to be oI type algebraic, but received |a, b, c| This doesn't work because cosine expects an algebraic expression, not a list.
Error, (in cos) expecting 1 argument, got 2 This mistake might come about iI you typed a comma instead oI a *. Error, missing operation What was this person thinking? Whatever it was, Maple doesn't know what to do with it. Error, unable to match delimiters Another delimiter message. Look Ior extra or missing parentheses. (7.5) (7.6)
This is what happens iI you Iorget the mandatory parentheses. There is no error message, but what Maple is giving you is the product oI Pi, the symbol "cos", and 1/4. One oI the ways you can tell that this isn't is what happens when you ask Maple to numerically approximate this expression. (7.7) (7.8)
This is the correct way to compute the cosine oI radians. The attachment at the end oI this chapter shows some oI the many other Iunctions available in Maple. Some oI them work on lists, sets, equations rather than on numbers or expressions. However, the same principle applies: they have a rule Ior taking the value oI their inputs (also known as arguments) and computing a result Irom them. 7.3 The textual names oI common Iunctions: doing math calculations using the keyboard. 107 7.3The textual names of common functions: doing math calculations using the keyboard. Some built-in mathematical Iunctions have textual names that are already quite Iamiliar Irom their use in mathematics textbooks: sin, cos, ln. Some are used so oIten that the most convenient thing to do is to remember their names. sqrt, abs, min, and max are straightIorward -- they are naturally thought oI as Iunctions and have names that are abbreviations oI the standard nomenclature. . Others, such as arcsin, or log10 have names that make sense but you'd have to look them up in the Maple on-line documentation to know. Table 7.2: Textual names for common math functions (7.9)
Maple knows "log10" is the base 10 logarithm. It automatically converts it into the equivalent expression using ln, the natural (base e) logarithm.
Many users will Iind it Iaster to type in the textual version oI plot than to use the plot builder. Furthermore, iI we want to change the expression or the range or labels oI the plot, it's easier to edit the text and re-execute the region than it would be with the clickable interIace.
(7.10) (7.11) max can Iind the maximum when all oI its arguments are numbers. max and min can do limited reasoning iI some oI the arguments are not numeric. For example, in the third example, Maple knows that abs(x)-2 is not going to be the maximum because abs(x) is must be larger. 108 7 Chapter 7 Using and DeIining Functions (7.12)
7.4A function name to commit to memory: exp The name oI the exponential Iunction in Maple is exp. Instead oI writing e`x, use exp(x). The textual doppelganger e`x does not work as a way oI calculating a power oI e, the base oI the natural logarithm (where "e" is just the letter typed at the keyboard, not augmented by command completion as described in the section on command completion (page 108) ). The orientation in college-level mathematics to view "a power oI e" as a Iunction is a pervasive change in point oI view Irom what you may have seen in high school. Making a point to use the new notation Irequently is the best way to make the switch. Table 7.3: exp is the name of the exponential function (7.13) (7.14)
exp(x) is the textual way oI writing "the symbolic constant e raised to the power x. Maple knows how to simpliIy symbolic expressions with the simplify assuming real operations in the clickable menu. (7.15) (7.16)
We can calculate powers oI e Irom the keyboard. For comparison we do the same calculation using the Common Symbols and Expressions Palette. While more oI a "sure thing", proIicient users would be able to get the keyboard version entered more quickly. (7.17)
We can enter an expression involving exponentials using only the keyboard. Maple will regard it as meaning the same thing as the expression entered using the combination oI the keyboard and the Palette. 7.5How can l remember so many functions7 Use command completion and on-line documentation. A well-developed system such as Maple, Matlab, or C# has thousands oI built-in Iunctions. You may need to use on a regular basis the names oI at least several dozen Iunctions to get your work done. The good news is that learning about Iunctions is not that taxing -- iI you own a scientiIic calculator you've already dealt with a situation where you can operate a dozen Iunctions. 7.6 Being savvy about using on-line documentation 109 A reasonable stance to take is to be Iamiliar (i.e. know "by heart") Iunctions and symbols that you oIten use and to be adept at using documentation to look up the details oI the ones that you need only occasionally. In exams and tests that let you use a computer, quick recall oI the most common will be useIul and expected. However, you should also expect to need to use additional Iunctions and inIormation that you haven't committed to memory. No one will expect you to memorize it all -- but they will expect you to be able to use it quickly anyway with the help oI on-line documentation. A quick-recall method Ior access to common Iunctions with textual entry is to type the escape key (Esc) aIter typing the Iirst Iew characters oI the Iunction's name. A pop-up menu will appear that will list possible ways oI completing what you typed. This is called command completion. Recall that you've already used this Ieature to enter symbolic constants such as e, the natural logarithm base. II what you are entering is a Maple operation such as solve, command completion will provide a textual template to Iill in the rest oI the arguments. It will also provide the parentheses required when entering Iunctional notation textually. Table 7.4: Command Completion
We type sol and then type the ESC key. A pop up menu shows option, including several Iorms oI solve. Clicking on one oI the options provides something to Iill out. We are not compelled to have a second variable oI x, it's just short-hand reminder that the second argument is the variable and the Iirst one is the equation. We can then go on to edit the "auto completed" template so that we turn the general Iorm into exactly what we need. 7.6Being savvy about using on-line documentation Experienced users reIer to the on-line documentation to help remember details about Iunctions. As has mentioned earlier, this is available through Help -~ Maple Help menu Ieature (key shortcut: press the control key and then the F1 key). II you recall a phrase or a name oI a Iunction, you can type it into the search Iield and the on-line help system will, like Google, produce the pages it has about your text entry. You can then explore Iurther by pressing links. Trying the examples typically given at the end oI the description is a good way to get a Iorm that you can use Ior your own purposes. 110 7 Chapter 7 Using and DeIining Functions Using on-line help
We want to Iind inIormation about how to use the inverse sine Iunction in Maple. We start up on-line help and type in "inverse trigonometric" into the search Iield, then hit the "search" button. The page we see does tell us that it's probably called "arcsin" but we'd like to see more. We see a link in the "see also" which we click on. This uncovers more links. The one that says "invtrig" seems promising so we click on that link.
This seems to be the page we want to spend time looking at. There are plenty oI examples at the bottom. 7.7 DeIining your own Iunctions with -~ (arrow) 111 7.7Defining your own functions with -> (arrow) Maple allows you to deIine simple Iunctions with the use oI -~. The general Iorm is function name : ( sequence of arguments) -~ expression that describes result . These can be entered through the Expression Palette, or textually. The arrow is entered textually by typing a - and then a ~, with no spaces separating them. We give an example oI Iunction deIinition in the Iollowing example. Table 7.5: A function definition in a math textbook Fruit Ilies are placed in a halI-pint milk bottle with a banana (Ior Iood) and yeast plants (Ior Iood and to provide a stimulus to lay eggs). Suppose that the Iruit Ily population aIter t days is given by
(a) What is the population aIter Iive days? (b) How long does it take Ior the population to reach 180? Analyzing the text, we see that it deIines a Iunction named P. It takes one input (argument), t, and produces as output whatever you get Irom evaluating the expression . Assuming that Maple understands the deIinition oI P like it does a built-in Iunction, then the description oI what happens when you evaluate P(5) would be: "Substitute 5 Ior wherever you see t in the expression . This gives you . PerIorm all the arithmetic and relevant simpliIications in this expression and return that as the result oI the Iunction." Even though 5 is an exact number, because there are limited precision numbers in the expression we expect that the result will be a limited- precision number. II the expression had only exact numbers in it, then the calculation would be done exactly. What we would like to do is to tell Maple about the deIinition oI P and use it in our work. We can do this through the clickable interIace. We anticipate reuse oI this Ior other days and population levels, and turn it into a parameterized script: Table 7.6: User-defined functions through the Expression Palette User-defined functions through the Expression Palette Commentary Start of parameters
The general Iorm is Irom the in the Expression palette. We alter slots in the template to mention the speciIic Iunction by name, the name oI the input, and the expression that describes how to calculate the output. 112 7 Chapter 7 Using and DeIining Functions User-defined functions through the Expression Palette (7.18)
(7.19)
End of parameters
(7.20)
Compute the number oI Ilies aIter days.
(7.21)
With this deIinition, we can compute P(5) using the natural mathematical notation. We plot the Iunction to see how the population grows. This is not needed by the problem but it helps us understand the situation better.
We can plot P(t) like we would any other expression. One the options to plot (see plot options in on-line help) is the ability to speciIy the title oI the graph by giving titlestring as an additional argument to the plot Iunction. Note that we are not using the clickable interIace to do plotting. 7.8 Using Iunctional evaluation instead oI using assignment or eval 113 User-defined functions through the Expression Palette
Compute when the population reaches desired level by solving the equation P(t)popLevel.
(7.22)
End of script
In anticipation oI using the value in later work, we assign it to the variable soln. We would then intend to take Iurther steps using soln. We could have deIined the Iunction textually just by typing P := (t) - > ... Iollowed by the rest oI the expression instead oI using the Expression Palette 7.8Using functional evaluation instead of using assignment or eval The problem with assigning variables is that it may cause unwanted side-eIIects, such as when trying to solve or plot with expressions involving those variables. We have seen in the section on eval (page 94) that we can use eval instead oI assignment, which saves us the chore oI having 114 7 Chapter 7 Using and DeIining Functions to assign and then unassign variables so that they remain as symbols when solving or plotting. We can more succinctly avoid this problem by deIining a Iunction based on the expression, and then causing evaluation to occur with standard Iunctional notation. Table 7.7: Comparing evaluation using eval and functional notation (7.23) (7.24) (7.25)
We set up an expression and then evaluate it at t4.7 seconds. (7.26) (7.27) (7.28)
We create a Iunction oI t using the arrow notation. We can then evaluate the Iunction at any value oI t that we want through the standard notation. This takes a little less typing than using eval. 7.8 Using Iunctional evaluation instead oI using assignment or eval 115
We can plot the Iunction Jf in a natural way. plot also has an abbreviated way oI plotting Iunctions -- just give the name oI the Iunction and the plotting range, and omit the name oI the Iunctional argument. You can read more about this in the on- line help Ior plot. 116 7 Chapter 7 Using and DeIining Functions 7.9Troubleshooting function definitions Function deIinition in Maple diIIers Irom the standard notation in high school mathematics This is because computers Iind it hard to detect the context where language is being used, so the same notation has to work both Ior mathematics and programming. The standard notation can't made be made to do this, so extensions and modiIications to the notation need to be made. (In other words, it's not a conspiracy to make your liIe harder gratuitously.) The technology that is standard in most computer language understanding systems needs to assign a unique meaning to input Irom the way it looks. Equations already use "" so iI you use I(x) ... Maple will understand you to be talking about an equation, not a Iunction deIinition. Use : when assigning a Iunction a name. Table 7.8: Troubleshooting function definitions (7.29) (7.30) (7.31) This deIines a Iunction Ior the gravitational attraction Iorce. m1, m2 and r are the arguments. g is another symbol used in the expression but it isn't included as an argument.
We deIine the value oI g. We expect not to change this while using the Iunction. We Iound the value by typing "gravitation" into Maple on-line help.
This calculates the attraction Iorce between a 1 kilogram and 2 kilogram mass that is 10 meters apart. The Iorce is in units oI Newtons. Error, invalid operator parameter name
This doesn't work at all. Do you see the diIIerence between the deIinition oI F and Fbad? One uses assignment : the other is either mistyped or mistaken.
(7.33)
This tries to use "" instead oI "-~" to deIine the Iunction FF. There is no error message, however, because this assigns FF an equation rather than a Iunction deIinition, which is perIectly valid, even iI it isn't what we were thinking oI. 7.10 Using Iunctions Irom library packages, with 117
(7.34)
We can tell that this supposed Iunction deIinition isn't working when we test it. When we try to use the Iunction in the usual way we don't get the number we were expecting, as with F(1,2,10). With testing, you veriIy, looking Ior evidence stronger than "no error message" that what you entered is what you want. (7.35)
This illustrates an alternative way oI deIining a Iunction, although it is not the Iorm recommend by these notes. Rather than "" as would appear in a math textbook, the assignment operation ":" is used instead. This produces the Iollowing pop-up:
Clicking "ok" to Iunction deIinition will create the proper Iunction deIinition, as the subsequent line oI the computation indicates. . (7.36)
Testing this Iunction deIinition, we see that we get the same result as with F 7.10Using functions from library packages, with As with other systems Ior technical computation, Maple has thousands oI built-in Iunctions. The deIinitions Ior some oI them such as cos or solve are automatically loaded into Maple when it starts up. However, iI all deIinitions were loaded, Maple would take a long time to start up and would require large amounts oI memory even beIore you had done any work in it. To avoid this, most Iunctions are loaded only when the user requests it. Most built-in Iunctions are organized into collections called packages. The general way to access a Iunction belonging to a package is through package[function]. The least squares Iunction belongs to a package named CurveFitting, hence its Iull name is CurveFitting[LeastSquares]. The with(package name) operation in Maple will load all the Iunctions in the speciIied package into Maple. AIter this operation, Iunctions can be reIerred to with just their "short name", e.g. LeastSquares rather than CurveFitting|LeastSquares|. Doing a with(package) can save you typing iI you expect to use a Iunction, or several Iunctions, Irom a package several times during a Maple session. Ending the line with a colon (:) will suppress printing oI all the Iunctions in the package that usually occurs. 118 7 Chapter 7 Using and DeIining Functions Table 7.9: with, the package loading operation
(7.37) (7.38) (7.39)
The CurveFitting package has a number oI Iunctions Ior data Iitting. One is called LeastSquares. However, LeastSquares(....) does nothing. Although there is no error message, this is a mistake -- we didn't load the package in with a "with" so the least squares data Iitting Iunction isn't known. We get the same kind oI behavior as iI we had typed in f(1,2,3) with f undeIined -- Maple just outputs what we typed in.
(7.40) Doing a "with" gives the names oI all the Iunctions in the package.
(7.41)
We can Iit a line to temperature as a Iunction oI pressure. (7.42) Once we do the with, LeastSquares works. 7.11Attachment: some built-in problem-solving functions The Iunctions in the Expression palette have the same name and work similarly to those described in math textbooks. The operations discussed in this attachment are also Iound in math textbooks, but they are usually not given Iunction names. It may seem novel to you that the rules Ior solving equations, Iactoring polynomials, or plotting can be collected together and given a Iunction name. Yet this way oI writing about such actions allows us to combine mathematics and programming. Thus solve, plot, factor, etc. are true Iunctions -- they have names, they are invoked with arguments, and return results that can be assigned to a variable. 7.11 Attachment: some built-in problem-solving Iunctions 119 Table 7.10: Textual names of common operations in Maple Function Textual name of function Example Commentary solve an expression or an equation solve (7.43) (7.44)
II there is more than one root, returns a sequence oI values solve an expression or an equation numerically fsolve (7.45) (7.46) Error, (in Isolve) a, b, c} are in the equation, and are not solved Ior
II there is more than one root, returns a sequence oI values
fsolve won't work iI the answer is not a number. plot an expression plot
Plot takes two inputs. The Iirst is an expression, the second is an equation naming the variable and the horizontal plot range.
120 7 Chapter 7 Using and DeIining Functions
plot may take more than two arguments, optionally. The rest oI the arguments are reIerred to as plot options. evaluate at a point (7.47) (7.48)
eval takes two arguments (inputs). The Iirst is an expression, the second is an equation or a list oI equations indicating what values to use Ior one or more variables in the expression. right hand side, leIt hand side oI an equation rhs lhs (7.49) (7.50) (7.51)
The third example shows that Maple thinks that "x0..10" is an equation even iI it isn't one in the standard mathematical sense. 7.12 Summary oI Chapter 7 material 121 approximate with a limited-precision number evalf (7.52) (7.53) (7.54) evalI has an optional second argument. II it's not there, Maple will compute a 10 digit approximation. II the second argument provided is a positive integer, then Maple will compute that many digits. convert between units convert (7.55) (7.56) (7.57)
convert does many things. When it is given Iour arguments and the second argument it units, then it expects the Iirst argument to be a number, and the third and Iourth to be expressions describing the units being converted Irom and to. Note that the units can be ratios or products rather than just names. 7.12Summary of Chapter 7 material Common mathematical functions (see on-line help for index of functions) sin, cos, tan, sec, csc, cot trigonometric Iunctions exp exponential Iunction (exp(x) means ) arcsin, arccos, arctan, arcsec, arccsc, arccot inverse trigonometric Iunctions sinh, cosh, tanh, .... hyperbolic trigonometric Iunctions ln, log10, log|b| logarithm, log base 10, log base b min, max minimum and maximum abs, sqrt absolute value, square root ceil, Iloor, trunc, Irac ceiling, Iloor, truncation, Iractional part Command Completion When entering math, type the Iirst part oI the name oI the Iunction and then hit the escape key. A pop-up window will appear with a list oI alternative competitions oI what you typed. Pick one, and a template will automatically be entered Ior you. Edit the spots oI the template to Iit your situation.
(then hit the ESC key)
122 7 Chapter 7 Using and DeIining Functions This is a way to get the computer to automatically type the right kind oI delimiters.
Defining custom functions with the arrow (->) notation Examples Create a custom Iunction by naming it and its parameters. A custom Iunction deIined using arrow notation is oI the Iorm:
In this case the Iunction name is P and its sole parameter is t. For multiple parameters, use the Iorm:
(7.58) (7.59) To call the Iunction, use the Iorm: (7.60) (7.61) To plot the Iunction, set the range oI an independent variable, and use it as a parameter to your custom Iunction. To solve the Iunction Ior a particular value, use the solve Iunction. (7.62) (7.63) Troubleshooting function definitions Error Examples 7.12 Summary oI Chapter 7 material 123 Troubleshooting function definitions Forgetting to use the assignment (:) operator. Error, invalid operator parameter name Using the equality operator () instead oI the arrow in Iunction deIinition. (7.65) Although technically not an error, deIining a Iunction without using the arrow notation is not prescribed by these notes. (7.66) 124 7 Chapter 7 Using and DeIining Functions 125 8Chapter 8 Programming with functions 8.1Chapter overview In computer languages, Iunctions or procedures are the building blocks Ior programming. An individual Iunction can be programmed to do a lot, but a single Iunction with a lot oI programming can be expensive and time-consuming to build. OIten a large program is built by combining Iunctions through daisv chaining -- by making the output oI one Iunction the input oI another. This is sometimes reIerred to as functional composition. Frequently used daisy chains can themselves be deIined as a Iunction, making them easier to reuse. Most computer languages extend the concept oI Iunctions to go beyond the numbers or Iormulas that "mathematical Iunctions" provide. In Maple, as in most languages, a Iunction can return other kinds oI results. It is Iairly common in Maple and other languages to have Iunctions that produce as output a list, an equation, or a string as a result. As we shall see, Iunctions can even return a plot as the result oI a Iunction. It is also possible Ior computer Iunctions to have lists, equations, plots, or strings as inputs. 8.2Designing functions from context In doing technical work, we oIten see Iunctions deIined as an equation relating the name oI the Iunction, its argument(s), and the Iunction deIinition.. Those are easy to translate into Maple's notation and use. For example iI we see in a mathematics book "deIine I(x) " then we can just transcribe it into the Maple Iunction notation: . In word problems, we have to "read between the lines" and design the Iunction. This requires answering the questions: a) What will the inputs to the Iunction be? Try to give symbolic names Ior it. b) What will the output be? Sometimes to realize what the output is, you can create a worksheet with several steps. II there is only one Iinal result, then that should be the output. c) How do you calculate the output Irom the inputs? HopeIully, there's a simple Iormula that describes this. We illustrate this process with an example: Designing a function for pressure/temperature problems Problem p. 180 in Introduction to Engineering by Jay Brockman, Wiley, 2009 The Ideal Gas Law, as stated in Introduction to Engineering ) is: (8.1) where P is pressure in Pascals (Pa) J is volume in . n is the amount oI gas in moles (mol), T is the temperature in degrees K, R is the gas constant, approximately . 126 8 Chapter 8 Programming with Iunctions We want to solve the Iollowing problem (actually, various versions oI it): Problem We measure the temperature and pressure oI a gas. It has a pressure oI 100 and a temperature 473 degree Kelvin. Then cool it so it has a pressure oI 89.8 . What is its temperature?.
Source: Introduction to Engineering by Jay Brockman, Wiley, 2009 (p. 180) Finding the answer First, we do the mathematical thinking and inIormal calculation that allows us to build a Iunction that will solve all problems oI this type: For a Iixed cylinder volume, according to the Ideal Gas Law: , so . so
Function design We see that the problem wants us to calculate a temperature given the atmospheric pressure , the internal pressure , and the Iirst temperature, . The output is , the inputs are , , and . We are Iree to name the Iunction anything we want since the problem statement doesn't name this. We decide to call it something that reminds us oI the purpose. (8.2) Testing and troubleshooting the function We see whether we get the intended result with the numbers we've already worked out. Note that iI we hadn't done the analysis, we wouldn't have any way oI testing what we designed. 8.2 Designing Iunctions Irom context 127 (8.3) That isn't the same result. What did we do wrong? The Iormula 1.2.2 seems like the right thing. What else could go wrong? Close inspection indicates that the Iirst argument to internalTemp is P1, which appears in the denominator oI the Iormula Ior the output. In (1.2.3), that would put the "89.8" in the denominator, but our example had 89.8 in the numerator. Oops, we gave the values in the wrong order Ior the Iunction. There's nothing wrong except that we should invoke the Iunction with the inIormation given in the correct order: (8.4) This result agrees with what we think the result should be Irom our previous calculations. Note that in testing Iunctions, it may be necessary to work through at least one calculation on your own in order to have a way to veriIy that the Iunction is working. Using the function We are given a diIIerent version oI the problem: We measure the temperature and pressure oI a gas. It has a pressure oI 2000 and a temperature 473 degree Kelvin. Then cool it so it has a pressure oI 53.6 . What is its temperature?. Answer: (8.5) Since the answer is in degrees Kelvin, this is only about 14 degrees above absolute zero. That's pretty cold! The usefulness of alternative function designs Suppose we had this new problem: We measure the temperature and pressure oI a gas. It has a pressure oI 100 and a temperature 473 degree . We then heat it to 512 degrees Kelvin. What is its pressure then? Another function designed A little thought produces the calculation:
This leads to the Iunction deIinition: (8.6) 128 8 Chapter 8 Programming with Iunctions We test this (remembering what happened beIore about the order oI arguments) (8.7) Conclusion To develop Iunctions, it helps to have worked through some typical calculations interactively. Once you have realized which quantities you are starting with and named them, and have developed the Iormula Ior the calculation using those names, you can create a Iunction deIinition. You can use the names given in the problem description, or you can make up names based on their purpose. Unlike mathematics, you are not limited to single letters Ior names oI variables or names oI Iunctions. Computer programmers know that longer names are oIten easier to remember or understand. 8.3Function composition: daisy-chaining functions together In the scripts we have developed so Iar, we have developed a result through a sequences oI actions. These sequences can oIten be described through Iunctional composition -- an expression that chains together several actions. Consider the Iollowing example: Problem On November 1, 2007, one Euro was worth US dollars. We are buying widgets that cost 30 Euros each and importing them into the US. We then put the widgets into packages that cost .075 dollars. How much should we sell the product in the US iI we want a 10 markup Irom our costs? Finding the solution: step 1, first do the calculation interactively. Doing this in the style oI scripts, we Iirst assign the values to variables, and then do the calculational steps. (8.8) (8.9) (8.10) (8.11) (8.12) (8.13) We Ioresee using this calculation several times as the conversion Rate, the manuIacturing cost in Europe, and the packaging cost change. We even see that the markup might change. We can try to boil down these steps into a Iew Iunctions. 8.3 Function composition: daisy-chaining Iunctions together 129 Designing the solution: step 2, design functions to do the calculational steps (8.14) (8.15) Note that the way that the third Iunction sellingPriceFunc is deIined, it daisy chains totalCostFunc and makes the output oI its invocation into one oI the inputs to priceFunc. Testing the solution: step 3, test the building blocks in the order that they are used We test the Iirst two Iunctions. AIter we see that they agree with our preliminary version oI the calculations, we test the third Iunction that depends on the correctness oI the Iirst two. (8.16) (8.17) (8.18) We could write a script that just used totalCostFunc and priceFunc, but by designing and using a third Iunction, we reduce the work oI handling an instance oI the problem to just pasting in the values Ior the Iour parameters in one line. This is probably less work than changing Iour lines oI parameters that we have had with our previous approach to scripts. While Iunction composition is a succinct way oI ordering many operations, its advantages are apparent only after the chain is built and tested as working correctlv. It maybe easier to develop the chain as a script oI assignments and then refactor -- rewrite without changing the meaning -- the script so that it uses user-deIined Iunctions to replace some oI the chains oI assignments. In this situation, the advantage oI reIactoring is that the user-deIined Iunction is much easier to reuse than a sequence oI assignments (which must be copied and edited Ior reuse). Using the solution: step 4, present a script that defines the functions, then invoke the "answer function" repeatedly to handle various versions of the problem Table 8.1: A script that uses functional (chaining), and its use Begin function definitions (8.19) 130 8 Chapter 8 Programming with Iunctions (8.20) (8.21) End function definitions
Problem solving
Version 1
On November 1, 2002, one Euro was worth US dollars. We are buying widgets that cost 30 Euros each and importing them into the US. We then put the widgets into packages that cost .075 dollars. How much should we sell the product in the US iI we want a 10 markup Irom our costs?
(8.22)
(We got the number Iormatted to currency by right-click-~Numeric Formatting-~Currency.)
Version 2
On November 1, 2007, one Euro was worth 1.4487 US dollars. We are buying widgets that cost 33 Euros each and importing them into the US. We then put the widgets into packages that cost .09 dollars. How much should we sell the product in the US iI we want a 10 markup Irom our costs?
(8.23) Version 3 8.4 Expressions with units oI measurements: convert 131
On November 1, 2010, one Euro was worth 1.4728 US dollars. We are buying widgets that cost 35 Euros each and importing them into the US. We then put the widgets into packages that cost .10 dollars. How much should we sell the product in the US iI we want a 8 markup Irom our costs?
(8.24)
By deIining our solution as a sequence oI Iunction deIinitions, we can solve several versions oI a problem just by invoking the Iunction with diIIerent parameters, without needing to copy lines oI calculations. 8.4Expressions with units of measurements: convert Maple has Iacilities Ior converting between various English and metric units. It is useIul Ior doing multi-step calculations because the conversions happen automatically. In the Iirst way oI using convert, one thinks oI a value as implicitly expressing a number oI units and wants another number expressing those number oI units converted to another unit. One uses convert( value, units, fromUnit, toUnit). Table 8.2: Examples of Unit Conversion Examples of unit conversion How many inches in a meter? How many Ieet in a kilometer? How many millimeters in a mile?
(8.25) (8.26) (8.27)
Note that the answer to this was expressed as a Iloating point number rather than a Iraction because the input was Iloating point (1.0) (8.28) Maple can convert between most compatible units. 132 8 Chapter 8 Programming with Iunctions Examples of unit conversion (8.29) (8.30) (8.31) Sometimes units are expressed as ratios oI other units. Maple can handle such conversions as well In many examples in the Maple documentation, some oI the arguments to convert are quoted -- surrounded by apostrophes -- to prevent evaluation Irom using the value oI the names oI the units. For example, iI you have assigned a value to the variable s, then you cannot convert to seconds with this name without quotation. Troubleshooting unit conversion (8.32)
As long as the various names used as arguments to the convert Iunction don't have values, things work Iine. Error, (in convert/units) unable to convert `min` to `259200`
Maple perIorms evaluation oI names as it Iigures out what the inputs to convert is. Since seconds has a value, Maple tries to compute convert(4, units, minutes, 259200). Since the 4th argument to convert has to be a name, an error results. (8.33)
Quoting the 4th argument causes the name seconds to be given as the 4th input to convert. This works. (8.34)
Quoting all the names as a prophylactic measure is acceptable. You see this in a lot oI the Maple on-line documentation. In Star Wars Episode IJ. A New Hope, Han Solo says that the Millennium Falcon made the Kessel Run in "less than twelve parsecs". We want to know how many days a parsec is.
Error, (in convert/units) unable to convert `pc` to `d`
This is the error message you see when you are trying to convert between incompatible units, e.g. trying to convert a gallon into a meter. pc seems to be Maple's internal name Ior parsec, d the name Ior days. 8.4 Expressions with units oI measurements: convert 133 Troubleshooting unit conversion
(8.35) A parsec is a non-Iictional unit oI distance, not time, so we can convert 12 parsecs to miles, kilometers, inches.... But we can't convert it to days any more than we can convert inches to volts. Table 8.3: A problem solved with a script using function definition A problem solved, a script built using function definitions A car travels a 45 miles per hour. How many minutes does it take to travel 900 kilometers?
(8.36) (8.37) (8.38) (8.39) (8.40)
We build a sequence oI calculations to understand how to solve this problem. This is the inIormal phase oI development, while we are trying to understand what to do. Once we have an idea, we start designing Iunctions and testing them. It would pretty obvious how to make a script out oI this to handle any problem oI the Iorm: A car travels speed miles per hour. How many minutes does it take to travel distance kilometers... With a Iew user deIined Iunctions, we can get the answer with less typing/cutting/pasting
(8.41) The Iirst step was to convert the distance Irom kilometers to miles. We create a Iunction that does it.
We test it to the result that we got in the script above and see that it agrees.
134 8 Chapter 8 Programming with Iunctions A problem solved, a script built using function definitions (8.42) (8.43) (8.44) The next step was to calculate the time (in hours) Irom the distance in miles and the speed in mph.
The test shows that tCalc seems to be built correctly. (8.45) (8.46) The third step was to convert the time Irom hours to minutes.
The test oI this step agrees with what the script does, too. (8.47) (8.48) The solution Iunction chains together the three Iunctions we've developed. This concludes the development and testing. We present a script and several solved problems in the Iigure below. The above table showed the thinking behind the design and testing oI the multi-step calculation. However, unless the reader wanted to see how the programming was developed, we wouldn't show the testing or the initial script. We would just the deIinition oI the Iunctions, and the results oI repeated invocation oI the "solution Iunction". Table 8.4: Solving multiple versions of a problem through functions Solving multiple versions of a problem through functions
Begin function definitions
(8.49) The travelSoln Iunction indicates the parameters oI the script, speed and distance. In setting up the solution method as a Iunction, we lose some intelligibility because oI the "inside out" style oI Iollowing the operation oI daisy-chained Iunction composition.
However, we gain convenience using the script. Using this Iorm makes it easier to see several solutions, because you don't have to wade through all the lines oI script that work out the 8.4 Expressions with units oI measurements: convert 135 Solving multiple versions of a problem through functions (8.50) (8.51) (8.52) End of function definitions
Problem version A A car travels at 45 miles per hour. How many minutes does it take to travel 900 kilometers?
(8.53) Problem version B A car travels at 45 miles per hour. How many minutes does it take to travel 452 kilometers?
(8.54) Problem version C A car travels at 65 miles per hour. How many minutes does it take to travel 1500 kilometers?
(8.55) answer, just a single line setting up the values oI the parameters and printing out the answer. 136 8 Chapter 8 Programming with Iunctions For casual unit conversion, it can still be useIul to rely upon Maple's encyclopaedic knowledge oI how to convert units. You can access this through Tools-~Assistants-~Unit Calculator Table 8.5: Unit Converter Assistant 8.5User-defined functions whose inputs and outputs aren't numbers Although you don't see much mention oI this in mathematics texts, it is Iairly common while programming to deIine and use Iunctions that take inputs and produce outputs that are not numbers. For example, iI we have a list L oI numbers, we can create a Iunction that takes a list as input and produces the average oI all the numbers as its output. Table 8.6: A function that takes a list as its input A function that takes a list as its input Example Commentary (8.56)
We are expecting the input to be a list oI numbers. As explained in More operations on lists (page 92), L|i| uses indexing to get the i-th value oI the list, and nops(L) is the number oI elements in the list.
(8.57)
When we invoke the Iunction, L is |5,7,-3,2,6|, so nops(L) is 5.
(8.58) With a diIIerent list as input, nops(L) is 7. Since at least one oI the elements oI the list was a limited precision number (5. has 8.5 User-deIined Iunctions whose inputs and outputs aren't numbers 137 A function that takes a list as its input a decimal point), the limited precision arithmetic is perIormed with it and subsequent steps oI the sum. In analyzing mathematical models as we have been doing, it is also useIul to produce abbreviations Ior common combinations oI plot options by creating a Iunction that produces a plot as its result. Table 8.7: A function that returns a plot as its output, rather than a number A function that returns a plot as its output, rather than a number Problem
We are given two lists oI data, pData, and tData. Plot pData as a Iunction oI tData, and vice versa.
Solution
Build a Iunction that becomes an abbreviation Ior the operations in the plot. Provide a third argument that is the string Ior the color.
(8.59) (8.60) (8.61)
Plot pressure versus temperature, in red. Note: there seems to be a bug in Maple that suppresses the printing of the horizontal axis label.
138 8 Chapter 8 Programming with Iunctions A function that returns a plot as its output, rather than a number Plot temperature versus pressure, in red. Copying and pasting the invocation of the PlotIt function we defined is easier than changing the insides of the original plot operation.
8.5 User-deIined Iunctions whose inputs and outputs aren't numbers 139 A function that returns a plot as its output, rather than a number
Because we have parameterized the data and the axis labels, it's easy to plot pressure versus temperature instead. We don't have to rewrite the directions in PlotIt, we just invoke it with the values and labels in reverse order.
140 8 Chapter 8 Programming with Iunctions A function that returns a plot as its output, rather than a number
It is possible to return a list or sequence as a result oI a Iunction. Such a Iunction can be put in a chain. Table 8.8: A problem solved with a function that outputs a sequence of two numbers A problem solved with a function that outputs a sequence of two numbers Problem A
A right triangle has a hypotenuse of length 5 feet. The angle between it and one of its sides is 10 degrees. What is the length of the perimeter?
We Iirst build a Iunction that computes the two sides oI the right triangle and returns the two values as a sequence. We have to convert degrees into radians in order to do this because the Maple trig Iunctions all use radians..
8.5 User-deIined Iunctions whose inputs and outputs aren't numbers 141 A problem solved with a function that outputs a sequence of two numbers (8.62)
Let's test the sideSide Iunction.
(8.63)
Now, develop a function that takes a sequence of three numbers and adds them together.
(8.64) By chaining together the output of sideSide and making it part of the input of sumSides, we can get the whole computation done in one function.
(8.65) (8.66) (8.67)
Problem B
A right triangle has a hypotenuse of length 10 feet. The angle between it and one of its sides is 42 degrees. What is the length of the perimeter? 142 8 Chapter 8 Programming with Iunctions A problem solved with a function that outputs a sequence of two numbers
(8.68)
Once we have done the work to design and test the Iunctions out on a problem, we can present a script that can solve several diIIerent versions oI the problem: Table 8.9: several versions of a function with function definitions Solving several versions of a function with function definitions Begin function definitions
A Iunction that computes the two sides oI a right triangle given the angle and the length oI the hypotenuse
(8.69)
A Iunction that takes a sequence oI three numbers and adds them together.
(8.70) Compute the perimeter by summing the three sides.
(8.71)
End function definitions
8.6 Chapter Summary 143 Solving several versions of a function with function definitions Problem A Solution
A right triangle has a hypotenuse of length 5 feet. The angle between it and one of its sides is 10 degrees. Approximately, what is the length of the perimeter in feet?
(8.72)
Problem B Solution
A right triangle has a hypotenuse of length 10 feet. The angle between it and one of its sides is 42 degrees. Approximately, what is the length of the perimeter in feet?
(8.73) 8.6Chapter Summary Function design Designing Iunctions Irom context a) What will the inputs be? b) What will the output be? c) How do we calculate the output Irom the inputs? Function composition (8.74) (8.75) (8.76) 144 8 Chapter 8 Programming with Iunctions Function design
Unit conversion Units can be converted directly into compatible units. (8.77)
Compound units expressed in ratio Iorm can also be converted into compatible compound units. (8.78)
Converting between incompatible units will generate an error message. Error, (in convert/units) unable to convert `d` to `mi`
II we create a variable with the same name as a unit, trying to convert using the variable name will throw an error.
To avoid this, we can use single quotes around the unit names to speciIy using the unit string, as opposed to the variable value. (8.79) Error, (in convert/units) unable to convert `d` to `5`
(8.80)
We can use Maple's built in unit converter to convert units using drop-down menus. This tool is located in Tools~Assistants~Unit Calculator Non-number inputs and outputs of a function Using a list oI numbers as an input (8.81) 8.6 Chapter Summary 145 Non-number inputs and outputs of a function (8.82)
Returning a plot instead oI a number (8.83)
Returning a sequence oI numbers instead oI a single number (8.84) (8.85)
146 8 Chapter 8 Programming with Iunctions 147 9Chapter 9 Visualization, modeling, and simulation 9.1Chapter Overview 1. Plot structures are the result oI the plot Iunction. They can be assigned to variables through : just as numbers, Iormulas, lists, and Iunction deIinitions, can be. 2. The displav operation oI the plots package allows you to combine together plots. OIten times a single picture can be more enlightening or easier to understand than looking at multiple pictures separately. 3. Simulation is the art oI predicting the behavior oI system entities as they change over time, through the use oI mathematical models. It can be as simple as using Iunctions that, given the time t as input, calculate the position, size, weight, or other changing properties oI a situation. With the appropriate mathematics, personal computer or supercomputer-class calculations can be used to come up with reasonably accurate descriptions oI phenomena. Computational simulations have become a mainstay oI modern engineering because "build it and see" can be much slower and more expensive to do Ior serious projects. 4. The animate operation oI the plots package is explained. Its use is illustrated with a session oI question-answering using a mathematical models oI moving bodies. Computer-generated animations are another useIul tool besides solve, and plot. 9.2plot structures Like solve, Maple plot is a Iunction: it has inputs and produces outputs. What kind oI output does the plot Iunction produce? In Maple, the result oI plot is a special type oI result called a plot structure. When you evaluate an expression in Maple that invokes the plot Iunction, a plot structure is created. As with any expression in Maple, you have the choice oI just typing in the expression in and seeing the result oI evaluating it, or assigning the value to a variable through :. Just typing in the plot expression displays the plot picture.When the plot structure is then assigned to a variable , then an ellipsis oI the plot structure is displayed rather than the plot picture. 148 9 Chapter 9 Visualization, modeling, and simulation Table 9.1: Plot results, displayed and not displayed Example Commentary
The plot structure result oI this operation is not being assigned to a variable through :. So Maple displays the structure in a pretty way -- by drawing a picture oI all the points and labels established by the plot operation and put into the plot structure.
(9.1) Evaluating an expression and then assigning it to the name p. This does not display the plot. We just see PLOT(...) which is a sign that the value oI p is a plot structure. 9.3 plots|display | and combining plots 149 Example Commentary Typing in p causes Maple to evaluate it. Since p's value is the plot structure assigned to it previously, Maple will display the plot. 9.3plots]display | and combining plots The display Iunction Irom the plots package takes as its Iirst argument a list oI plot structures. It will produce a plot structure that combines all the plots together. displav is the way to get a multi-plot in a script without doing cutting and pasting oI plots. Table 9.2: Display combines plots display combines plots (9.2) (9.3)
Someone we know has used a variant on LeastSquares Curve Fitting, to derive a Iormula with that Iits the data. We wish to plot both the data points and the Iormula on a single graph. 150 9 Chapter 9 Visualization, modeling, and simulation display combines plots
This is the point plot we get Irom this data. (9.4) p1 is assigned the plot structure oI the point plot. Because the result is assigned to the variable p1, only an ellipsis oI the plot structure is displayed rather than the picture oI the plot. (9.5)
Let's assume that we have a Iriend who has done curve Iitting to timeData and tempData and gotten this Iormula. In ENGR 101 Fall 2010, Matlab was used to do exponential curve Iitting like this. We could replication that calculation in Maple, but don't show it here. II you're interested in seeing how to do it, ask your instructor about it. (9.6) p2 is assigned another plot structure, the smooth plot oI the Iormula. We skip the step where we show this plot as a separate picture because we are more interested in seeing it combined with the point plot. We load the plots package. Because we ended the line with a colon (:), the list oI Iunctions in the package is suppressed. In general, ending a line with a colon suppresses the normal output. 9.4 plottools, lines, and other shapes 151 display combines plots displav's argument must be a list oI plot structures. This Iorm oI the operation will take all the plots and superimpose them together. This is a good way to have a multi-plot in a script. 9.4plottools, lines, and other shapes The plottools package has a number oI Iunctions that are useIul Ior inclusion in visualizations (plots). For example, you can create a line segment oI any desired color and line thickness with the line function. One can then use the displav Iunction to merge together lines, plots, and other shapes. The on-line documentation on plottools contains links to Iurther description. Table 9.3: BROKEN - MISSING TITLE! We create a bit oI "modern art" by drawing a circle and a point plot. (9.7) As the on-line documentation indicates, the Iirst two arguments to line are lists indicating the coordinates oI the starting point and ending point oI the line segment. There are optional arguments that indicate color and line thickness, etc.
152 9 Chapter 9 Visualization, modeling, and simulation (9.8) (9.9) We suppress printing oI the plot structure CURVES(....) Ior c3 with a colon because it's long and we don't want to see it, we want to see the picture it describes. Note that Maple exposes its Canadian roots by using "colour". One oI the options to plot (and display) is to not show the axes. Another option is to indicate that the scaling should be constrained to be equivalent in both horizontal and vertical directions (to make the circle look like a circle). That gives us an unIramed work oI art!
9.4 plottools, lines, and other shapes 153 We can use lines and circles Ior less Irivulous purposes, too. Table 9.4: Combining a line with other plots using display (9.10)
(9.11)
We create a plot structure that is a green line segment running between the points (12,25), and (12, 58).
154 9 Chapter 9 Visualization, modeling, and simulation
We combine the line with the data and curve p1 and p2 we created in Combining Plots (page 149). This highlights the value oI the curve at t12 minutes, which would be good graphic design iI we were to include this in a report on a situaiton where that time was oI special interest.
9.5Mathematical models and simulation Mathematical models try to describe a "real" situation in terms oI equations and Iormulae. The point oI modeling is to try, through mathematical or computational means, to determine what will happen without having to run experiments in the "real" situation. As Dr. Jay Brockman oI the University oI Notre Dame says in his book Introduction to Engineering. Some engineering students have been Iortunate enough to participate in pre-engineering programs such as the Iirst LEGO(TM) League robotics design competition or American Society oI Civil Engineering bridge-building contests. In addition to Iostering creative problem-solving skills, such projects also introduce students to the important notion that seemingly good ideas don't always work out in practice. OIten in such programs, students have ample opportunity to test and modiIy their designs beIore they Iormally evaluate them. II the design doesn't work, then like a sculptor working with clay, the designer adds something here or removes something there until the design is acceptable.
This cut-and-try methodology is also sometimes used in industry, particularly in circumstances where the design is simple, or where, the risk or cost oI Iailure is low. In many situations, however, there is no second chance in the event oI Iailure. For engineering systems such as buildings, bridges, or airplanes -- top name just a Iew -- Iailure to meet speciIications could mean a loss oI liIe. For others -- such as the integrated circuit chip -- the cost oI Iabrication is so high that a company may not be able to aIIord a second chance. In these situations, it's critical Ior the engineering team to be highly conIident that a design will be acceptable before it's built. To do this, engineers use models to predict the behavior oI their designs. A model is an approximation to a real system, such that when actions are perIormed on the model, it will respond in a manner similar to the 9.5 Mathematical models and simulation 155 real system. Models can have many diIIerent Iorms, ranging Irom physical prototypes such as a crash-test dummy to complex computer simulations.
We can think oI a mathematical model as a kind oI virtual system... whose input is a set oI variables that represent either aspects oI the design or aspects oI the environment, and whose output is a set oI variables that represent the behavior oI the system. Inside is a set oI mathematical relationships that describe the operation oI the system.
Jay B. Brockman, Introduction to Engineering, John Wiley and Sons, 2009. pp 151-152. The point oI expressing a situation mathematically is to use mathematics and computation to better understand the situation. Usually we are given or derive a Iormulas that allow us to calculate key properties oI the system. For models involving only a Iew variables, this can involve the Iollowing kinds oI actions: 1. Get a single number, by evaluating a Iormula or Iunction. 2. Get a single number, by solving an equation. 3. Gain an understanding oI a relationship between one or more entities oI interest and the"input variables" by producing a Iormula. 4. Gain a visual understanding oI the relationship by plotting a Iunction, or possibly several plots merged together. 5. Gain an understanding oI how a a system changes over time. Rather than computing the value oI a variable once, we repeatedly compute the value oI the variable at several diIIerent points at time. This is called computational simulation oI the system. We can view plots changing over time by producing an animation. Examples of the first four types of computation Third type: producing a formula In the temperature-pressure data fitting example (page 118) the mathematical model is the Iormula that expresses the relationship between temperature and pressure. We had only data and no Iormula to begin with, but we developed the Iormula using the CurveFitting|LeastSquares| operation. This was a computation oI the third type mentioned above.. First type: Evaluating a formula or function Once we had the Iomrula, we used the relationship to calculate pressure at several given temperatures. This was a computation oI the Iirst type mentioned above. Second type: solving an equation to get a desired value We also Iound a temperature corresponding to a speciIied pressure by using solve -- a computation oI the second kind mentioned above. Fourth type: visualization (plotting) In the example with an exponential curve fit (page 149), we got a visual impression oI how the Iormula Iit the data by combining the point plot oI the data and the plot oI the Iormula together -- the Iourth kind oI computation mentioned above. We haven't explained how to do the IiIth type oI computation -- animation -- yet. This will be discussed in upcoming section Animations (movies) using animate (page 158) 156 9 Chapter 9 Visualization, modeling, and simulation 9.6Drawing x-y position as a function of time through parameterized plots The mathematical models oIten describe the position oI a system entity as a Iunction(s) oI time. II the entity's position is two dimensional, then we have two Iunctions, oIten called x(t) and v(t). We can generate a plot oI position Ior various values oI t with a special Iorm oI plot. plot( [ x-position expression, v-position expression, var low..high], plot options) will draw a two dimensional graph connecing the (x,y) points traced out Ior the values oI the expression as the variable var takes on values between low and high. Table 9.5: Examples of plots where the x and y positions are parameterized by t Examples of plots where the x and y positions are expressions parameterized by t Example 1 In this example, we describe the x and v positions as periodic Iunctions oI time. Every time units, the positions return back to where they were originally.
(9.12) (9.13) We plot the position using parameterized plotting. By deIault the scaling used Ior the horizontal and vertical axes are diIIerent, but in this case the deIault makes the graph look misleadingly like a circle when it should look more like an ellipse. To compensate, we use the scalingconstrained option to plot.
9.6 Drawing x-y position as a Iunction oI time through parameterized plots 157 Examples of plots where the x and y positions are expressions parameterized by t Example 2
In this example, we have parameterized expressions Ior an object shot out oI a cannon with horizontal velocity 10 Ieet/second and vertical velocity 10 Ieet/second minus the acceleration due to gravity.
(9.14) (9.15) 158 9 Chapter 9 Visualization, modeling, and simulation Examples of plots where the x and y positions are expressions parameterized by t 9.7A first animation example using animate, animation controls Let's look an animation. First we have to create it. We can use the animate Iunction oI the plots package. For the time being, let's not worry the details oI why the operation is entered the way it is. Rather we Iocus on what the animation is trying to do, and how to view it in Maple once it has been created. Table 9.6: First animation example This produces a movie oI a point moving through the points (0,0), (.1, .01), (.2, .04), etc. up to (10, 100).
9.7 A Iirst animation example using animate, animation controls 159
II we click on the plot, the Maple tool bar changes and shows us animation controls. Table 9.7: Animation controls
These controls are highly similar to video playback controls Iound in many applications (e.g. You Tube), so we won't discuss at length here. Note that using them you can: 1. Start playing the animation. 2. Stop the animation. 3. Display only a particular Irame, "Irozen". 160 9 Chapter 9 Visualization, modeling, and simulation 4. Control the number oI Irames per second it plays. 5. Set it to play once or continually repeat in a loop. See Graphics-~Animation-~Animation Toolbar under the Table oI Contents oI the on-line Maple help. Right-clicking on the animation will also produce a menu oI operations that provide an alternative Ior controlling the animation. Table 9.8: Animation pop-up menu Animation pop-up menu II we play the animation, we will see a point move upwards in a parabolic path: Table 9.9: Frames 1, 5, 10, 20, and 25 of the animation Frames 1, 5, 10, 20, and 25 of the animation
9.8 The Iirst animate example, part 2 161 Frames 1, 5, 10, 20, and 25 of the animation
9.8The first animate example, part 2 Now that we've gotten the general idea oI what animates results are like, let's look again at what was entered and look at the details oI what was computed. The general Iorm oI the operation is: General form of the animate operation with(plottools): animate(plotting function, | parameters to plotting Iunction|, time variable time range) What this does is to apply the plotting Iunction to the parameters Ior various values oI the time variable. Each value oI the time variable used is a separate Irame oI the movie. In the previous section we used: In the Iirst Irame oI the movie, it used the value t0 Ior the time variable t. Thus it plotted plot(|0|,|0|,stylepoint, color"Purple"); plots a small circle at the coordinate (0,0). The next time value used is t0.4667. The second Irame oI the movie is the result oI plot([.41667], [.416672], stylepoint, color"Purple"); which plots a small circle at the coordinate (.41667, ). 9.9Designing a function to use in animate In this section, we explore the design oI a Iunction that we use with animate to create an animation. 162 9 Chapter 9 Visualization, modeling, and simulation Problem Create an animation oI a circle whose radius expands Irom r1 at time t0 to r5 at time t10. Solution The actions we create are a short script that deIines a Iunction drawCircle(t) . Then it uses it in animate. While we there are other ways to use animate other than this style, we choose to do things this way because the drawCircle Iunction allows us to test the plotting one Irame at a time beIore we try to create the animation. Solution, part 1
First, we Iind Irom the on-line documentation Ior plottools that the Iunction circle(|a,b|,r, color"red") draws a circle centered at the point (a,b) with radius r: While this seems to do the job that we wish Ior the starting Irame, we have to consider how this will vary as t0 to t10. We want the radius oI the circle to be 1 when t0 (as in the Iigure above), and 5 when t10. We can do some line Iitting to come up with the Iormula iI we can't remember enough high school algebra to Iigure it out ourselves: Figuring out the formula for the radius as a function of time
(9.16)
We plot the Iormula we get Irom the data Iitting with the data points to convince ourselves that the line agrees exactlv with 9.9 Designing a Iunction to use in animate 163
the two points. We'd get a similar result Ior curve Iitting a line any time we Iit a line with only two data points. (9.17) Testing the solution function (9.18)
We can create a Iunction that creates a circle oI the appropriate size given a value Ior t; 164 9 Chapter 9 Visualization, modeling, and simulation
We try this Iunction out at a t0.
The Iunction evaluated at t5 looks the same, but we see Irom the axis labels that it is actually a bigger circle 9.9 Designing a Iunction to use in animate 165
The Iunction evaluated at t10 draws a circle oI radius 5, as it should. Once we are convinced that the Iunction drawCircle works Ior the range oI values oI t that we need it to, we can use it in animate. The way we invoke drawCircle within animate is diIIerent than when we were using it one Irame at a time. The name oI the Iunction is kept separate Irom the parameters, and the range. This delays the creation oI any plot structures until animate starts computing them. Complete script solving the "expanding circle animation" problem (9.19) We see the Iirst Irame oI the animation below. When we click on the animation, the animation toolbar appears and we can then play it. We see the circle expand over time. Unlike the individual plots we created during our testing, all the circles use the same scaling. 166 9 Chapter 9 Visualization, modeling, and simulation
Some frames from the expanding circle animation
9.10 Designing a more elaborate animation 167 9.10Designing a more elaborate animation Problem A satellite is in a circular orbit around the earth, at a distance oI Iive earth radii. Create an animation oI it circling. Solution -- discussion We will create a Iunction drawPlanetAndSat (t) that Ior any time t draws both the Earth and the satellite at time t. We browse through the on-line plottools package and discover the Iunction disk(c,r, color....) that draws a solid disk whose center is at the point c, has radius r, and speciIied color, in a Iashion similar to the circle Iunction we used in the Designing a function to use in animate (page 161). Browsing through on-line help Ior the color names known to plot reveals that one color is "DarkKhaki". We decide to draw the Earth as a disk oI radius 1 centered at (0,0). Drawing a disk 168 9 Chapter 9 Visualization, modeling, and simulation
We decide to represent the satellite as a point. Recall that (cos(t), sin(t)) describes circular motion moving around a circle oI radius r1. To parameterize orbital motion at radius 5, we use (5*cos(t), 5*sin(t)). Drawing a point at (0,5) 9.10 Designing a more elaborate animation 169
We can combine the two together using displav. Drawing a disk, and a point at (0,5) We invoke displav with a list oI two plot structures: the disk, and the point plot. AIter we draw this we see the two plots together, but it isn't exactly what we want, because the horizontal and vertical scaling is not equal. 170 9 Chapter 9 Visualization, modeling, and simulation
We include the plot option scalingconstrained as an extra argument to displav. 9.10 Designing a more elaborate animation 171 We're almost done. As with the animation design oI the previous section, we write a Iunction oI t that describes the disk and the position oI the point at time t. A function describing a frame to draw at time t (9.20)
We test this Iunction out at a Iew values oI t. The idea is that the satellite makes one orbit during the period t0.. . 172 9 Chapter 9 Visualization, modeling, and simulation
We now can use this Iunction with animate to draw the orbiting satellite. Complete script to solve the "orbiting satellite animation problem" 9.10 Designing a more elaborate animation 173 (9.21)
We have the animation have the satellite circling three times. Some oI the Irames oI the animation can be seen in the table of frames from the orbiting satellite animation (page 173). Table of selected frames from the orbiting satellite animation
174 9 Chapter 9 Visualization, modeling, and simulation 9.11Solving a problem with the help of animation Problem A boy throws a ball straight up in the air with an initial velocity oI 15 miles per hour. Once released, the ball's position is described by the Iunction , where is the initial velocity, and g is the Iorce oI gravity, . (a) How many seconds does the ball stay in the air? (b) Generate an animation that shows the ball's motion. t should be measured in seconds, and position in Ieet Irom ground level. Assume that the ball starts at 0 Ieet altitude even though this would be unrealistic Ior a boy to do unless he was standing in a pit! (c) Use the animation to determine roughly when the maximum altitude is, and what that altitude is. (d) Find how Iast the initial velocity should be so that the ball goes up over 30 Ieet. Solution First convert 15 miles per hour into a velocity in Ieet per second using the convert Iunction Iirst described in the section on problem solving functions in Chapter 7 (page 121). (9.22) DeIine the gravitational constant (9.23) Next, deIine the Iunction Ior position. 9.11 Solving a problem with the help oI animation 175 (9.24) Doing a rough plot oI position versus time shows us roughly when the ball will hit the ground. We guess that it might take three seconds. Table 9.10: A rough-draft plot of ball versus time.
(9.25) That's too much. The answer seems to be about 1.4 seconds, but we can use solve to come up with an exact value. (9.26) There are actually two solutions. The obvious one is when t0 and the ball hasn't yet been thrown. The non-obvious one is the larger one. To get that one, we daisy-chain the max Iunction with solve. (9.27) This answers part (a) oI the problem. We veriIy our computation by evaluating x at that time and Iinding that the position oI the ball really is at altitude 0. 176 9 Chapter 9 Visualization, modeling, and simulation (9.28) Now we need to make the movie. We need to create a Iunction which Ior time t, draws a point at the coordinate (0, x(t)). To illustrate what we mean, let's compute the position oI the ball at t1 second. (9.29) We want the ball to be at position (0,6). A plot command that would do this would be: Table 9.11: A plot that draws a ball as a circle at (0,6). We've drawn the circle larger (symbolsize30) to make it stand out. 9.11 Solving a problem with the help oI animation 177 Similarly, at t.5, the ball's position would be at x(0.5): Table 9.12: A plot that draws a ball as a time t0.5.
Evidently x(.5) is 7. We create a user-deIined Iunction that creates a plot structure as a result. (9.30) Let's try this out Ior t.5 and see iI we get the same result. 178 9 Chapter 9 Visualization, modeling, and simulation Table 9.13: Trying out a function that draws the ball at a particular time. We can now use this Iunction with animate. Note that we needed to compute flightTime in order to make the movie run exactly as long as it takes Ior the ball to come back down to the ground. Table 9.14: Animating the ballFrame function to produce a movie of the ball in flight. 9.11 Solving a problem with the help oI animation 179
This answers part (b) oI the problem. By playing the movie, we see that the maximum altitude is about 7.5 Ieet, at time t0.687 seconds. This answers part (c) oI the problem. To answer part (d), we need to do more programming. We Iirst modiIy the plot so that it draws a line segment at 30 Ieet as well as plotting the position oI the ball. We use the line Iunction oI the plottools package discussed in Plottools section (page 151) to draw a line segment at (-5,30) to (5,30), and to color it green: (9.31) (9.32) The display Iunction can be used to combine this line with a Irame oI the movie. Here is an example oI this: Table 9.15: A ball with a vertical target line.
180 9 Chapter 9 Visualization, modeling, and simulation The automatic scaling oI plot chops oII the vertical distance between 6 Ieet and 0 because there is nothing in this Irame that needs that. In the animation, the scale is adjusted so that all Irames operate in the same axes. Now we can create a new user-deIined Iunction that plots both the line and the ball. (9.33) To look at the behavior oI the ball at a particular velocity, we can now execute a two line script, consisting oI assigning v0 to the desired initial velocity, and then the operation that draws the movie. Table 9.16: A first try at shooting the ball up 30 feet: 15 miles per hour (9.34)
9.11 Solving a problem with the help oI animation 181
As we already have seen, is not Iast enough. We set it higher and recalculate the movie: Table 9.17: Second try: shoot upwards at 22 feet per second (9.35)
We can continue with trial-and-error. All we need to do is vary the velocity parameter. The reusability oI the ballWithLine Iunction is heavily exploited. 182 9 Chapter 9 Visualization, modeling, and simulation Third and Iourth tries: shoot upwards at 40 and 45 Ieet per second (9.36)
(9.37) (9.38) According to the movies, 45 Ieet per second seems to be about right. We could get a more precise determination through movie-watching, but Ior high accuracy we should use more mathematics. In a subsequent chapter, we will introduce additional Maple operations that can calculate the velocity exactly (or a close approximation) without the trial-and-error oI movie watching. However, using the movies did give us a better understanding oI the phenomenon, and allowed us to do trial-and-error Iairly easily. 9.12 Exporting animations and non-animated plots 183 9.12Exporting animations and non-animated plots One operation available in the popup menu is Export. Right-click (or control-click) -~ Export -~ Graphics Interchange Format will produce an animation Iile in .giI Iormat. As the animation Iile is being created, a dialog box will appear asking you to speciIy the directory where the .giI Iile should be written. Once created, the Iile can be included on web pages or other documents. This Ieature is also available Ior ordinary (non-animated) plots. Right-clicking (control-click Ior Macintosh) will create a Iile oI the plot in .giI. .jpeg, or .ps Iormat. However, .giI Iile is the only Iormat oI the three that is supported by web browsers Ior animations. Table 9.18: Exporting animations through the pop-up menu 9.13Summary of Chapter 9 Combining plots and shapes using display Supplying the displav Iunction with a list oI two or more plots will cause those plots to be plotted on top oI one another. We can save a plot in a variable to display later.
Marking a speciIic value on the plot can be accomplished using the line or circle Iunction. (9.39) (9.40)
184 9 Chapter 9 Visualization, modeling, and simulation Parameterized plots For plots that may have values corresponding to 2d positions, we use multiple Iunctions to deIine both and (9.41) (9.42)
We put these Iunctions in a list, along with the range oI the independent variable , and plot. Animating plots using animate Creating an animation 9.13 Summary oI Chapter 9 185
Controling the animation using the animation tool bar or the animation popup menu The animation tool bar is located above the workspace window, while the popup menu can be displayed by right-clicking the animation. Exporting an animation to a graphics Iile Right click animation~Export~Graphics Interchange Format 186 9 Chapter 9 Visualization, modeling, and simulation 187 10Moving into programming 10.1Chapter Overview The interactive document interIace that we've worked with so Iar is good Ior quick development oI calculations involving a Iew steps. Because Ieedback occurs aIter each step entered, this style oI working is oIten the Iastest way oI getting such short calculations done. We've also seen how the eIIort to develop a script can be made to yield greater payback by Iinding and exploiting situations where reuse with minor editing and re- execution. With longer scripts or extensive re-execution, editing and execution (other than oI the entire worksheet) becomes tedious even iI we are saving time by having the computer do the calculations. In this chapter, we introduce a new way oI entering and executing scripts: code edit regions. While such regions make it more convenient to work and execute blocks oI Maple instructions, the programmer must enter things using the textual version oI Maple expressions and operations. Individual lines must be separated by semi-colons (;) so that the Maple language processor can more easily tell where one instruction ends and the next begins. With code edit regions, the programmer must also work harder to see how the state oI the computation is changing during the computation, rather than only looking at the Iinal output.. This is because iI the Iinal result is wrong, the programmer must Iind at what point in the script mistakes (called program bugs) occur. Work with code edit regions oIten requires adding print statements into the script to better see changes in variables and intermediate results. As our Iirst extended experience with code edit regions, we look at the CarSimulator package used Ior the Iirst two labs oI CS 122. To use it, two new programming elements are needed: procedures (blocks oI code that are delimited by proc()... end proc) and conditional loops (blocks oI code that are delimited by while condition do ... end do). Procedures (multi-line Iunctions) and loops are used in most programming languages and in many oI the programs that we will write Irom this point onwards. 10.2Code edit regions: entering a block of code, executing it all at once We have seen that even some oI the easiest technical calculations break down into a series oI operations, chained together. Realizing that we will typically need the computer to perIorm a "series oI operations" is the motivation Ior making the transition to programming, where execution oI many operations in a block is typical. The Maple document interIace that we have been using so Iar easily supports calculations where the user prompts to computer to do a series oI steps by positioning the cursor at the Iirst operation and then hitting return (or enter) repeatedly. We now introduce a second way to enter instructions and have them executed as a block. This alternative is oIten easier to work with when you have a Iew dozen instructions and will want to execute them all in a chain. One can open a text Iield in the Maple document where one can enter a series oI instructions. To do this, position your cursor where you want the text Iield to appear in the document, and with the mouse perIorm Insert-~Code Edit Region Insert->Code Edit Region menu 188 10 Moving into programming Once the Iield has been created, you can type the textual version oI the Maple instructions you want executed. Each instruction (commonly reIerred to as a statement) must be separated by either a semi-colon, or a colon. II the statement ends in a semi-colon, then its value will be printed during execution oI the region. II the statement ends in a colon, then printing oI its value will be suppressed just as it is in operation oI documents. Once all the instructions have been entered, you can run them all in a series by typing control-e (command-e on Macintosh), or by entering right- click-~Execute Code (on Macintosh, control-click-~Execute Code). Instead oI typing control-e, you can as an alternative click on the "!" icon on the Maple toolbar. (The "!!!" icon executes the entire worksheet, including all code edit regions.) The results Ior each statement will appear below the region in blue, except Ior the statements whose printing is suppressed by a colon. The output in blue is reIerred to as the execution trace produced when the code region's actions are carried out. Execute Group icon ("!" icon) on Maple Toolbar
10.2 Code edit regions: entering a block oI code, executing it all at once 189 Any portion oI a line that begins with a "#" is a program comment. The rest oI the line is regarded by Maple as something that people will read, not an instruction to be perIormed by the computer. Typically what appears aIter the # is commentary written in English (or whatever language is convenient Ior communication with the intended audience) that helps explain/remind human readers what a segment oI code is about. As you read programs with comments, you will see that some programmers are "chattier" than others. This is because they Ieel that their intended reading audience needs more explanation. In proIessionally written code, you will oIten see comments at the beginning oI the region that give an overview oI what the code region does, the name oI the author(s), and the date oI creation/modiIication. ProIessional organizations oIten mandate a particular style and content Ior such "header" comments, so that it will be easy to Iind inIormation about any code written by several programmers working on a single project. An example from Chapter 7 as a code edit region Code region Commentary
#We reset Maple so previous assignments are ditched. restart; #We assign two variables with pressure and #temperature data. pData := [134.2, 142.5, 155.0, 159.8, 171.1, 184.2]; tData := [0, 20.1, 39.8, 60.0, 79.9, 100.3]; #Load in the package with(CurveFitting); #Develop a linear formula for temperature #as a function of pressure. pressureFormula := LeastSquares(tData, pData, t); #We can also fit a line to pressure as a function # of temperature. Segments oI lines that begin with # are regarded as program comments (Ior the program reader's eyes), not operations Ior Maple to carry out.
Separate actions are separated by semi-colons.
The results in blue are displayed aIter we position the cursor in the code edit region and type control-e (command-e on Macintosh), or enter Execute Code Region via the clickable menu.
The code region will develop a scroll bar iI the amount oI text entered exceeds the size oI the window. The size oI the Iield can be adjusted by right click-~Component Properties, and then modiIying the integers listed Ior the width and height. Enlarging a code Region window by changing component properties via the clickable menu 10.2 Code edit regions: entering a block oI code, executing it all at once 191 192 10 Moving into programming The "Collapse Code Edit Region" menu item oI the clickable menu will reduce the entire window to an icon. II the Iirst line oI the region is a program comment, it will be listed to the right oI the icon. Clicking on the code icon will execute the code within. A collapsed code edit region Code region Commentary
# Figure 11.1.1 #initialize variables i := 1; val := .3; #evaluation point term := (val^i)/i!; # a term to compute print("term is", term); #message s := term; #s has a copy of the term tol := 10e-7; #A small value. We collapsed the region by positioning the cursor in the code region window, and then entering right click-~ Collapse Code Edit Region. Note that the comment on the Iirst line becomes displayed next to the code edit icon. 10.3 Troubleshooting common errors in entry into code edit regions 193 (10.2) 10.3Troubleshooting common errors in entry into code edit regions New kinds oI errors and warnings can appear in code regions, due primarily to the new requirement that statements be separated by semi-colons and colons. Trying to enter too many lines at once beIore testing what you have so Iar can make older errors appear more mysterious. Table 10.1: BROKEN - MISSING TITLE! Code regions with entry errors Example Commentary
a := sin(3.5 + cos( Pi/2) ; Error, `;` unexpected
(Above region with Iixes) a := sin(3.5) + cos( Pi/2) ; (10.3)
The error message indicates that a semi-colon was not expected where Maple scanned it. This is typically semi-colons can appear only at the end oI a complete Maple statement. This message typically indicates that something went wrong in what was entered beIore the semi-colon. Edit the code region to make the statement correct, and re-execute the region.
The problem here is a missing parentheses ). To Iix this, you'd put a closing ) aIter the "3.5", and then re-execute the region with a control-e(or command-e).
a := sin(3.5) + cos( Pi/2) Warning, inserted missing semicolon at end of statement (10.4)
This is only a warning, and executing this region does perIorm the computation correctly.
a := sin(3.5) + cos( Pi/2) b := cos(3.5) + sin( Pi/2) Error, missing operator or `;` II we add another line without a semi-colon between, we get just an error. Both lines are messed up because Maple needs an explicit separator between the statements. Just putting the next instruction on another line is not enough. 194 10 Moving into programming
(Above region edited with Iixes) a := sin(3.5) + cos( Pi/2) ; b := cos(3.5) + sin( Pi/2); (10.5)
a := sin(3.5 + cos( Pi/2) ; b := cos(3.5) + sin( Pi/2); Error, `;` unexpected
II you try to enter several lines at once beIore entering, you have the additional problem oI Iiguring out which line the mistake occurred on. In this case, you have to decide which oI the two semi-colons was unexpected.
Fortunately, you can sometimes get some help iI you are observant -- the cursor will oIten Ilash on the line where the problem is Iirst noticed (the Iirst line in this case).
a := sin(3.5 + cos( Pi/2) Warning, premature end of input, use <Shift> + <Enter> to avoid this message.
There's both a missing closing parentheses and a missing semi- colon here. The symptom is that there is a warning message (which isn't necessarily a sign oI trouble, but is here), plus the Iact that you are expecting a value to be printed Irom the computation but just see a red "~" with no numeric output.
Fixing both problems and re-executing the region will produce the correct result.
a := sin(3.5 + cos( Pi/2) b := cos(3.5) + sin( Pi/2); Error, missing operator or `;` Sometimes when you enter a line, you make more than one error. Even though the same mistake has been made as in the previous example, there is a diIIerent error message than beIore. Executing this region causes the message indicated, plus the cursor will be observed to Ilash at the start oI the second line.
Rather than being in an "I was expecting more" state which produced the Iirst warning message, Maple is in a "I was expecting more, but wait what I've seen isn't what I was expecting". Since there's nothing beIore the cursor started Ilashing beIore any oI the second line was parsed, it means that the error must have happened beIore that on the previous line. 10.4 print and annotating an execution trace 195
There are still two things to Iix. Fixing them will produce two lines oI output. 10.4print and annotating an execution trace While executing a code region is convenient, a disadvantage is that the output oI a result is separated Irom the line oI code that produced it. Furthermore, many lines oI output are not very useIul other than as conIirmation that an intermediate action didn't Iail. As is true with interactive operation oI Maple, ending a line with a colon (:) instead oI a (;) will suppress the output. print(....) will cause a line oI output which will list the value oI each item between the parentheses. The programmer can tailor the use oI each to produce more intelligible inIormation. An example from Chapter 7 as a code edit region Code region Commentary
#We reset Maple so previous assignments are lost. restart; #We assign two variables with pressure and #temperature data. pData := [134.2, 142.5, 155.0, 159.8, 171.1, 184.2]: print("Pressure data is:", pData); tData := [0, 20.1, 39.8, 60.0, 79.9, 100.3]: print("Temperature data is:", tData); #Load in the package with(CurveFitting): #Develop a linear formula for temperature #as a function of pressure. pressureFormula := LeastSquares(tData, pData, t): print("Fit of temperature to pressure is:", p=pressureFormula); #We can also fit a line to pressure as a function # of temperature. tempFormula := LeastSquares(pData, tData, p): print("Fit of pressure to temperature is:", t=pressureFormula); (10.6)
This is the same computation as the previous example, but the programmer has tailored the output to make the execution trace more intelligible. The execution trace output oI most oI the assignments is suppressed with a colon, as is the listing oI the operations Irom the with. print statements have been added to make the results more intelligible. Since the result oI Least Squares does not name the dependent variable, we tweak the output to include that as well as the result oI the least squares calculation.
196 10 Moving into programming 10.5The CarSimulator package: a first view Let's see an example oI working with a package that requires us to write Maple programs in code regions. We are given the problem and a place to work out its solution as a Maple worksheet with multiple code edit regions. Executing the Iirst region does Simulator Set Up -- initializing some oI the variables and data structures needed Ior the simulator to work. It also loads in the CarSimulator package (in the Iile CarSimulator.mla, which must be in the same directory as the worksheet we opened up). Table 10.2: First code edit region for CarSimulator work Problem: run the simulator in a 20 x 20 empty arena, so that the car moves Iorward one square, turns leIt, and then moves Iorward two squares.
#Code region #1 #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator); (10.7)
AIter loading the package, Maple on-line help Ior it is also available. Clicking on the CarSimulator Iolder in the table oI contents Ior on-line help indicates that there are several levels oI help. For example, under Setup we some oI the operations mentioned in the Iirst code region. Under Car Operations we see move and turn. As with the rest oI on-line help, clicking on any oI the entries will bring up a help page with a Iurther description. We realize that using a typical system's package, with dozens oI Ieatures, will require doing more reading oI on-line help to get the details oI Ieatures we are likely to need. 10.5 The CarSimulator package: a Iirst view 197 Table 10.3: On-line help for CarSimulator after package is loaded into worksheet Executing the second region sets up and shows the arena. The arena has a rectangular coordinate system. The car typically starts at coordinate (1,1) Iacing rightwards. The orientation oI the car is given in radians, and the initial orientation is 0 radians. The arena is shown by calling the package operation carMovie with argument stateTable (a Ieature oI the simulator that we could read about iI we looked Iurther in the Data Iolder oI the package). Table 10.4: Second code edit region with Car Simulator
198 10 Moving into programming #Code region #2 #We don't put a restart here because we want to #remember what we did in the previous code region. #To start afresh, rerun all of the regions. #Initialize car simulator initialize(); establishBoundaries(20,20): #draw a 20 x 20 sandbox for the car to roam around in. Coordinates range from [0,0] to [20,20]. drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration
10.5 The CarSimulator package: a Iirst view 199 We want to have the car move Iorward one square and turn leIt,and then move Iorward two more squares, like this: Table 10.5: First control program: move, turn left, move twice. At start AIter a one square move (partial image zoom in) AIter turn in place AIter another move AIter last move To do this, we write a control program named run1a. The program consists oI a script using operations Irom the CarSimulator package. The arguments we give to turn we derive Irom the inIormation Iound in the on-line help page: a leIt turn requires an argument oI a/2 radians. We see some new syntax in the control program: the control script is bracketed by proc() and the phrase end proc. This deIines the script as a procedure. A procedure is a way oI encapsulating a script so that it has a clearly deIined beginning and end, along with named parameters. A procedure is expected to name parameters and optionally have a result, like the Iunctions deIined by the arrow notation described in chapter 7. run1a needs no parameters, which is why it has ( ) rather than a parenthesized parameter sequence ( x) or (tData, pData). For the next chapter all oI our procedures will have no parameters, but we will eventually visit situations where we need to write procedures that need one or more parameters. Table 10.6: Second code edit region with Car Simulator
#Code Region #3 run1a := proc() move(1); #move forward one square turn(Pi/2); #turn Pi/2 radians (left 90 degrees) move(1); #move forward one square move(1); #move again. end proc: run(run1a); (10.8)
AIter deIining the control procedure Ior the car, we submit the procedure (by its name, run1a) to the run operation oI the CarSimulator package. The execution trace indicates that the simulation has taken 4 moves. However, there is no indication oI what happened in the trace. To see the simulation at work, we again perIorm the operation carMovie(stateTable). Because the simulation had multiple moves, this now causes an animation window to appear which when played displays the movement oI the car Irame-by-Irame. The animation is created by the Maple programming in the package -- we will learn how to make movies in that Iashion in a Iew chapters. Table 10.7: Fourth code edit region with Car Simulator animation result
#Code Region #4 #Play an animation of the results of the simulation. #After the "run", the stateTable has all the information #needed to make the animation. 200 10 Moving into programming carMovie(stateTable);
The worksheet with the Iour code regions thus sets up the arena Ior the problem, describes the control procedure that is the solution to the stated problem, and shows the results oI running the simulator with the procedure, which demonstrates that it solves the problem. 10.6A second task with the CarSimulator We set up a more elaborate arena (set up code not shown): #Establish an arena restart; libname := ".", libname; with(CarSimulator): #Set up the problem. Note that by parameterizing the problem we can use random #numbers to set up sizes and locations to vary the problem a little. size := 30: #width and length of the sandbox. k := 15; L := 12; h := 10: y := 10: distanceBetweenWalls := 10: 10.6 A second task with the CarSimulator 201 wallHeight := 5: #parameters for location and sizes halfDistance := floor(distanceBetweenWalls/2): halfHeight := floor(wallHeight/2): initialize(); pickAStart := 3:
#Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ k+pickAStart,y,0,CARNORMAL]: CURRENTLOCATION := [ k+pickAStart,y,0,CARNORMAL]: #draw walls setBackground([seq('[k-halfDistance, y+i],[k+halfDistance, y+i]',i=-halfHeight..halfHeight)], BARRIER): establishBoundaries(size,size): #draw a sandbox for the car to roam around in. Coordinates drawBackground(): print("Starting configuration is:"); carMovie(stateTable); 202 10 Moving into programming
The goal is to move Iorward until the barrier is reached, then turn around and move Iorward until the opposite barrier is reached. The control program, illustrated in the Iollowing code region, uses two new programming elements, while and isTouching. A description oI the isTouching Iunction can be Iound in the on-line help Ior the CarSimulator package. isTouching is a Iunction that returns true or false -- truth or Boolean values, rather than a number, Iormula, or plot structure as we have seen with other Iunctions. while is part oI the programming language notation Maple uses to describe a loop. Programming loops typically contain a block oI actions that are to be perIormed a number oI times, as well as a continuation condition that allows the computer to decide whether to continue to perIorm the block. The decision to repeat the loop is done typically only at the start oI the would-be repetition. Once the decision is made to do it, the whole block is perIormed beIore the continuation condition is considered again. barrierBounce := proc() while not(isTouching(0, 'bt')) do move(1); In the loop in the control program, the block consists oI the single action "move(1)". Thus the loop tells the simulated car 10.6 A second task with the CarSimulator 203 end do;
turn(Pi); #turn around
while not(isTouching(Pi, 'bt')) do move (1); end do; end: run(barrierBounce); print("Simulation result is:"); carMovie(stateTable); to check iI the Iront oI the car is touching a barrier. II not, it moves Iorward one square. Repeating the loop means to check the continuation condition again and then perIorm the block's actions. Thus this loop perIorms check-move-check-move- check-move.... stopping when the next check determined that the Iront oI the car is touching a barrier.
Once the loop is over, the program will perIorm the next action listed, which is the turn. AIter that, there is another loop which does the check-move-check.... repetition until the other barrier occurs.
At the start (partial image zoom in) Taking several more moves to the wall, and and turning. (zooming in some more) Taking several moves towards the other wall At the Iinish -- touching the other wall. 204 10 Moving into programming 10.7Programming to solve a class of problems At this point, those oI you not be Iamiliar with while may be wondering why we go through the trouble oI writing a loop with a conditional expression when we can just build something that has exactly the right number oI moves and turns:
#Something that solves one kind of arena lessRobustSoln := proc() move(1); turn(Pi); move(1); move(1): move(1): move(1): move(1): move(1); move(1); move(1); end proc: However, consider the Iollowing similar arena problem (details oI set up code hidden in code edit region): #We're not resetting everything, but we will initialize with a new arena #Set up the problem. Note that by parameterizing the problem we can use random #numbers to set up sizes and locations to vary the problem a little. size := 40: #width and length of the sandbox. k := 15; L := 12; h := 10: y := 10: distanceBetweenWalls := 20: wallHeight := 5: #parameters for location and sizes halfDistance := floor(distanceBetweenWalls/2): halfHeight := floor(wallHeight/2): initialize(); pickAStart := 7:
#Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ k+pickAStart,y,0,CARNORMAL]: CURRENTLOCATION := [ k+pickAStart,y,0,CARNORMAL]: #draw walls setBackground([seq('[k-halfDistance, y+i],[k+halfDistance, y+i]',i=-halfHeight..halfHeight)], BARRIER): establishBoundaries(size,size): #draw a sandbox for the car to roam around in. Coordinates drawBackground(): print("Starting configuration is:"); carMovie(stateTable); 10.7 Programming to solve a class oI problems 205
Our "less robust" solution won't work here because the number oI moves is diIIerent. II we tried to write a similar program that would solve this new arena, it would get a bit tedious repeating the "move(1)" instruction the necessary number oI times. However, the original solution barrierBounce will work Iine: run(barrierBounce); print("Simulation result is:"); carMovie(stateTable); 206 10 Moving into programming Building a program that Iits exactly one situation means that you will have to reprogram it iI the situation changes. II you're going to go through the eIIort oI building something, it will pay to design Ior a reasonable amount oI Ilexibility. For that reason, appropriate testing oI a program will put it through its paces in a number oI diIIerent situations, to check that the desired breadth is really there. 10.8Reviewing old and introducing new programming concepts The Iirst two labs oI CS 122 uses a package called the CarSimulator. It allows you to write simple programs that control a simulated car moving around an obstacle course. The simulator is useIul Ior rapidly prototyping ideas Ior controlling an actual robot car. Using the CarSimulator on a problem requires the use oI elements oI Maple programming that we have already seen: Element First introduced in Chapter Assignment 4 Lists 5 Scripts 5 Library packages 7 On-line help 6 10.9 Summary oI Chapter 10 207 Textual entry oI actions 6 Functions 7,8 Animations 9 Code edit regions 10 We will also get a Iirst look at some new elements: Element Discussed further in Procedures 11 While loops 12 Methodical testing and troubleshooting code blocks 13 Tables 14 For loops 15 If -then-else statements 16 10.9Summary of Chapter 10 Example Commentary Use of print
(10.13)
(10.14) We set up a list oI values. L has all Iloating-point values because the "10.0" in the denominator causes all computations to be done using limited- precision arithmetic. The display oI the value oI L is suppressed because we ended the assignment with a colon.
print prints out the sequence oI values given to it as arguments. You can give any number oI items in the sequence. The commas separating the string and the number are Irom the sequence. Note that as Iirst mentioned in the section in Chapter 7 on including external packages (page 117), the result is not displayed because the line ends with a colon. Code edit regions Insert -~ Code Edit Region to create a region. control-e (command-e in Macintosh) or right-click -~ Execute Code in a code edit region to execute all the code in it. 208 10 Moving into programming right-click-~Component Properties to open a dialog box with the dimensions oI the code region (in pixels). Change these dimensions by entering diIIerent numbers to enlarge or shrink the box. Sorry, dragging will not resize the code region. right-click-~Collapse Region to turn the code region into an icon.
Clicking on the icon will then execute the code inside.
The Iirst line oI code appears as the label Ior the icon.
right-click-~Expand Region to turn a code region icon to display the region again. Semi-colons and colons All Maple statements must be separated or terminated with either a semi-colon (;) or a colon (:). Usually each statement executed generates a line oI output which appears in blue aIter the region. This sequence oI output is called the execution trace oI the code. II a colon is used, then the output that normally results Irom evaluating the statement is suppressed Irom the execution trace.
Comments Any portion oI a line oI code starting Irom a number sign (#) is treated as commentary and not as an operation to be perIormed.
Example Commentary
# Figure 11.1.1 #initialize variables i := 1; val := .3; #evaluation point term := (val^i)/i!; # a term to compute print("term is", term); #message s := term; #s has a copy of the term tol := 10e-7; #A small value. (10.15) Segments oI lines that begin with # are regarded as program comments (Ior the program reader's eyes), not operations Ior Maple to carry out.
The results in blue are displayed aIter we position the cursor in the code edit region and type control-e (command-e on Macintosh), or enter Execute Code Region via the clickable menu.
Result oI Iirst assignment (to i) 10.9 Summary oI Chapter 10 209 Result oI assignment to val. Result oI assignment to term. Result oI calling the print Iunction. Result oI assignment to s. Result oI assignment to tol. CarSimulator package loading
#Code region #1 #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator); (10.16)
To successIully use the CarSimulator, the CarSimulator.mla and CarSimulator.hdb library Iiles need to be located in a directory speciIied by the variable libname. Assigning libname to include ".", and then opening and working on a worksheet located in the same directory as the library Iiles will work.
You can tell that when the loading works iI the with (ending with a semi-colon rather than a colon) produces a list oI all the items included in the simulator package.
Only do a restart iI you want all previous assignments to be erased. CarSimulator initialization
#Code region #2 #We don't put a restart here because we want to #remember what we did in the previous code region. #To start afresh, rerun all of the regions. #Initialize car simulator Some actions are necessary to initialize the simulator beIore it is used. Typically they are CarSimulator set up actions such as initiali:e and establishBoundaries. 210 10 Moving into programming initialize(); establishBoundaries(20,20): #draw a 20 x 20 sandbox for the car to roam around in. Coordinates range from [0,0] to [20,20]. drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration
Control procedure for car control barrierBounce := proc() while not(isTouching(0, 'bt')) do move(1); end do;
turn(Pi); #turn around
while not(isTouching(Pi, 'bt')) do move (1); end do; end: A procedure begins with proc( ) and ends with proc end. The procedure contains a number oI actions such as move and turn, although it can contain any other Maple operation such as assignments, print, or calculations.
A control loop within a procedure is oI the Iorm while condition do action, action, .... end do; 10.9 Summary oI Chapter 10 211
II the condition is true, then the actions are perIormed. Then the condition is evaluated again. II it is still true, the actions will be repeated. This continues until the condition is Iound to be Ialse when it is evaluated. The conditionis evaluated only once per repetition oI the actions, at the start.
CarSimulator simulation and visualization of results
run(barrierBounce); print("Simulation result is:"); carMovie(stateTable); Use the run operation oI the CarSimulator, giving it the name oI a control procedure that has been previously created. AIter the simulation is over, see the results by applying the carMovie operation oI the package to the stateTable generated by the simulation. 212 10 Moving into programming 213 11More on proc and while 11.1Chapter Overview We continue our discussion oI programming with two new elements, procedures and loops under the control oI while. Procedures are an alternative way (compared to the -~ notation) oI creating a Iunction. As with all Iunctions, they take arguments and returns results. Unlike arrow notation Iunctions, their deIinition can span more than one line oI code, including control constructs such as while. Procedures can have local variables, whose use is encapsulated. This allows a procedure programmer to use a variable Ior internal use during a procedure execution and not have to worry about interIering with the use oI that variable outside oI the procedure. 11.2Review of function terminology Although they don't use the same syntax, procedures are a kind oI Iunction. The technical terminology oI procedures shares a lot with the terminology we have already used Ior Iunctions. Let's review what we know Iunction terminology in Maple. Review of function terminology 1. Functions process input values and produce an output value. The Iunction definition describes how the values oI those parameters are used to compute a Iunction result. When we deIined Iunctions using the -~ (arrow) notation, the result was described as an expression involving arithmetic, structure creators such as | |, and built-in (e.g. sin, sqrt, or seq) Iunctions or Iunctions previously deIined by the user. The names given to the symbols used Ior the input values are called the formal parameters to the Iunction. Functions can have zero or more parameters.
The function result is typically the expression computed by the Iunction.
There are two Iormal parameters to the Iunction deIined above. a, and b are their name.
2. Functions are associated by a name by making the Iunction deIinition the right hand side oI an assignment statement. The Iunction is named f through the assignment. 3. DeIining a Iunction does not perIorm the computation, it just stores the directions Ior how to do the computation within the computer. AIter a Iunction is deIined, you can get the computer to perIorm the computation by invoking the function. Invocation involves giving the name oI the Iunction, and values Ior the Iunction's arguments, enclosed in parentheses. The values supplied to the Iunction when it is invoked are called the actual parameters or arguments to the Iunction.
# The actual parameters (arguments) # are 3.1 and 4. We can combine the actions oI several Iunctions together by composing (also known as daisv-chaining ) them. Rather than the "one aIter another" sequencing oI actions that we might get Irom using Iunctions on several lines oI a script, Iunction composition uses "inside out" sequencing. This is the same as the sequence
214 11 More on proc and while
Programming languages Ieature Iunctions (and procedures) prominently because oI their advantages in the construction oI programs. Writing a computation as a Iunction encapsulates it: there is a well-deIined starting point given by the values supplied Ior the parameters, there is a speciIic computation described within the Iunction deIinition, and there is a Iinal result to the computation when the Iunction delivers its output. Only when the Iunction is later invoked are those actions perIormed. The Iunction may be invoked multiple times (as would occur when the users invokes it when doing several problems, or when map is used with a Iunction) aIter it is deIined. The expectation oI reuse is one oI the justiIications Ior the extra work needed to deIine a Iunction, since re-invocation is typically easier than even copying and pasting the actions. 11.3Creating a short function with proc... end One line Iunctions created by -~ have the limitation that we can't create Iunctions that have code which includes assignment, loops, or other actions that require more than one line oI code. In the previous chapter, we saw the use oI proc ()... end proc Maple procedure definition -- the simplest form function name : proc (formal parameters ) statement, statement, ... (one or more)
end proc; The procedural result is by deIault the last thing computed in the sequence oI actions computed by the Iunction when it is invoked. Example: The simple function defined with -> and then again with proc
This is a Iunction named f deIined using the arrow notation. f2 has the same behavior as f. Note that there are no local variables here -- all the symbols that appear in the Iunction come Irom the parameters.
Note that you can end a procedure with either "end" or "end proc". 11.4 Creating a Iunction with encapsulated (local) variables 215 11.4Creating a function with encapsulated (local) variables General form of a Maple procedure definition with local variables function name : proc ( formal parameters ) local variables used within procedure; statements, end proc; Notes 1. There is no semi-colon between the proc ( ) containing the Iormal parameters and the word local. II there are no local variables Ior the procedure, then you need to put in the semi-colon: proc ( formal parameters ) ; statements, .... 2. The opposite oI a "local variable" is a "global variable". We don't use them much in the Maple procedures we will be working with. You can read more about them iI you look up "global" in Maple on-line help. 3. You can't assign a value to a Iormal parameter in the statements oI the procedure. parameters are used only as a way oI providing input inIormation to the Iunction. Usually local variables arise when the Iunction needs to compute and store intermediate results that are used Ior the Iinal answer but are not part oI them. An important Ieature oI local variables is that use oI their use inside the Iunction is encapsulated . When a variable is declared to be a local variable oI a Iunction, the value that the symbol outside oI the Iunction invocation may have is temporarily set aside. The local symbol within the Iunction starts oII with no value, but may be assigned values within the programming oI the Iunction. Once the Iunction invocation is over, the old value that the symbol had is restored to it. Table 11.1: Demoonstrate of assignment of local variables Demonstration that local variables do not pay attention to assignments made outside the scope of the procedure definition. #This function demonstrates the use of local variables. testFunction := proc() local i; print("Line 1: i's value is",i); i := 1; print("Line 2: i's value is",i); end proc; We deIine a testFunction, whose purpose is to assign a value to i, and to print out it's value beIore and aIter assignment.
#This is a "non-local" use of i; i := 0; print("Line 0: i's value is",i); testFunction(); print("Line 3: i's value is",i);
The execution trace we get Irom executing this code region aIter the previous one is explained by:
a) the Iirst zero is Irom the assignment to i. 216 11 More on proc and while b) The "Line 0" output is the assigned value oI i. c) Once testFunction begins execution, the declaration oI i as a local variable means that previous assigned values are temporarily set aside. This is why the Line 1 output is just i. d) The Line 2 output reIlects the assignment within testFunction. e) The Line 3 output comes aIter the invocation oI testFunction is completed. By that time, the previously assigned value oI i is restored. The behavior oI local variables is seems more complicated, but the reality is that it Irees the programmer Irom having to worry about the whether their use oI a variable in a Iunction will break other code outside oI the Iunction iI they don't restore the previously assigned value. One could avoid local variables iI one never used Iunctions or procedures, but this isn't practical Ior serious projects -- the complexity oI coding will deIeat the attempt to complete the project successIully without the ability to break the task into the smaller pieces that coding with procedures allows. 11.5Conditional repetition through while... do... end do The key understanding oI loops written with while is: "keep on repeating this while a condition is true". The general form of the while statement while condition do loop bodv; end do; The condition is something that is either true or false. An error results iI it isn't. The condition is evaluated only once per repetition, at the start beIore any oI the code in the loop bodv is executed. II the condition is true, then the entire loop bodv is executed. II not, the repetition is Iinished and execution moves onto the next instruction aIter the end do.
The condition is evaluated at the start oI the loop iteration. It does not matter iI the condition changes in the middle oI the loop bodv; this won't terminate execution oI the loop until the execution reaches the end oI the loop bodv and thecondition looked at again beIore the start oI the next repetition oI the loop.
The continuation condition is can be a Iunction invocation that returns true or false, such as the isTouching or onTopOfSign Iunctions oI the CarSimulator package. It can also be an inequality such as x.1 or abs(y-z)~ tol. It always must be an expression that can be evaluated to be true or false. II the inequality is numeric such as x .1, variables in the condition such as x must have been assigned a numeric value earlier in the Maple session.
11.6 Example: car control procedures with conditional expression built Irom Boolean operations and multiple loops 217 It is also possible to combine several conditions together using the operations and, or, and not(....).
true and false are reIerred to as Boolean values (aIter the British 19th century, George Boole -- http://www.gap-system.org/ ~history/Biographies/Boole.html Ior more inIormation). Functions that return Boolean values are reIerred to as Boolean functions, while and, or and not are reIerred to as Boolean operations. 11.6Example: car control procedures with conditional expression built from Boolean operations and multiple loops The problem here is to go to the Iirst Iour way intersection, and turn leIt. AIter the turn, go Iorwards to the target. Here is a sample scenario. We want to write a control program that will work this scneioar as well as with similar ones. The similar scenario will have a Iour way intersection and a target to the leIt, but it may have a number oI other (three way) intersections beIore that. The distance to the Iour way intersection may vary between scenarios.
#Generate test problem (code not shown) #Turn left at the first 4 way intersection, go to target. #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator): StringTools[Randomize](); randomize(): #Pick a starting location for the car xStart := 5: yStart := 15: #Pick typical distance to intersection reach := 20: #Pick distance to target intersection distance := rand(reach-4..reach+4)(): #Distance to target yTarget := rand(5..10)(): #Initialize car simulator initialize(): #Size of arena 218 11 More on proc and while arenaSize := 40: #pick two intersection locations L1, R1:= op(combinat[randperm]([seq('2*i',i=1..floor(distance/2)-1)])[1..2]): establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. #Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ xStart,yStart,0,CARNORMAL]: CURRENTLOCATION := [xStart,yStart,0,CARNORMAL]: minLR := min(L1,R1): maxLR := max(L1,R1): #draw wall to a first intersection setBackground([seq('[xStart+i, yStart-1],[xStart+i, yStart+1]',i=0..minLR-1)], BARRIER): #draw wall to a second intersection setBackground([seq('[xStart+i, yStart-1],[xStart+i, yStart+1]',i=minLR+1..maxLR-1)], BARRIER):
#draw wall to a third intersection setBackground([seq('[xStart+i, yStart-1],[xStart+i, yStart+1]',i=maxLR+1..distance-1)], BARRIER):
#Draw wall to the end setBackground([seq('[xStart+i, yStart-1],[xStart+i, yStart+1]',i=distance+1..min(arenaSize- xStart-2,2*distance))], BARRIER):
#Draw wall at intersection setBackground([seq('[xStart+distance-1, yStart+i],[xStart+distance+1, yStart +i]',i=1..min(arenaSize-yStart-2, distance))], BARRIER):
#Draw left wall at intersection setBackground([seq('[xStart+L1-1, yStart+i],[xStart+L1+1, yStart+i]',i=1..min(arenaSize- yStart-2, distance))], BARRIER):
setBackground([[xStart+L1, yStart-1]], BARRIER): 11.6 Example: car control procedures with conditional expression built Irom Boolean operations and multiple loops 219
#Draw right wall at intersection setBackground([seq('[xStart+R1-1, yStart-i],[xStart+R1+1, yStart-i]',i=1..min(yStart-2, distance))], BARRIER):
setBackground([[xStart+R1, yStart+1]], BARRIER): setBackground([seq('[xStart+distance-1, yStart-i],[xStart+distance+1, yStart- i]',i=1..min(yStart-2, distance))], BARRIER): drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration
220 11 More on proc and while The car will automatically stop when it is pointing at and directly next to a blue target, so the control program should just run the car Iorward while it hasn't seen the 4 way intersection, then turn and run Iorward until it is touching the target. We can express "not at a Iour way intersection" by using Boolean operations to construct the condition that the car is touching something in one oI the Iour directions -- (istouching(-Pi,'bit')) or (isTouching(Pi/2,'bt')) or (isTouching(0,'bit')) or (isTouching(-Pi/2,'bt')); goToFourWay := proc() while isTouching(-Pi,'bt') or(isTouching(Pi/2,'bt')) or (isTouching(-Pi/2,'bt')) or (isTouching(0)) do move(1); end do; turn(Pi/2); while not(isTouching(Pi/2,'bt')) do move(1); end do; end proc: run(goToFourWay); carMovie(stateTable); 11.7Example: car control procedures with a local variable Our scenario here is to go around Iour corners in a counterclockwise direction, then stop. 11.7 Example: car control procedures with a local variable 221
#Generate test problem #Turn left at the first 4 way intersection, go to target. #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator): StringTools[Randomize](); randomize(): #Pick a starting location for the car xStart := 5: yStart := 15: #Pick lengths of rectangle bottomTop := rand(4..10)(); leftRight := rand(4..10)(); #Initialize car simulator initialize(): #Size of arena arenaSize := 40: establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. #Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ xStart,yStart,0,CARNORMAL]: CURRENTLOCATION := [xStart,yStart,0,CARNORMAL]: minLR := min(L1,R1): maxLR := max(L1,R1): #draw bottom and top walls setBackground([seq('[xStart+i, yStart+1],[xStart+i, yStart+leftRight]',i=0..bottomTop)], BARRIER): #draw left and right walls setBackground([seq('[xStart, yStart+i],[xStart+bottomTop, yStart+i]',i=1..leftRight)], BARRIER): drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet 222 11 More on proc and while carMovie(stateTable); #Show initial configuration
We present two solutions to this. The Iirst solution repeats the code that says "move Iorward while touching the wall to the leIt, then turn leIt" Iour times. Since the isTouching operation uses absolute rather than relative directions, we must change the angle with each turn Irom to to to 2 . We do this by introducing a local variable "angle" that we increment by Pi/2 each time. The reason why we do the incrementing angle : angle Pi/2; rather than just angle : Pi/2; angle : Pi; angle : 3*Pi/2, etc. will become clear in the sequel. turnFourTimes := proc() local bt,angle; #Move forward while touching a wall, then #turn left #Initial scan angle is Pi/2 angle := Pi/2; 11.7 Example: car control procedures with a local variable 223 while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); angle := angle+Pi/2; #angle is now Pi #Do that again. while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); angle := angle + Pi/2; #angle now 3*Pi/2 #Do that again. while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); angle := angle+Pi/2; #2*Pi is same as 0. #Do that one more time while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); end proc: run(turnFourTimes); 224 11 More on proc and while carMovie(stateTable); 11.8Example: the four corner problem with a shorter program using a nested loop In the previous example, our solution involved describing the actions needed to traverse one side oI our Iour sided problem, then repeating that code Iour times. We write a shorter program by putting all oI this inside a loop, whose purpose is to perIorm everything inside it Iour times. #Generate test problem #Turn left at the first 4 way intersection, go to target. #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname: #Load CarSimulator package with(CarSimulator): StringTools[Randomize](): randomize(): 11.8 Example: the Iour corner problem with a shorter program using a nested loop 225 #Pick a starting location for the car xStart := 5: yStart := 15: #Pick lengths of rectangle bottomTop := rand(4..10)(): leftRight := rand(4..10)(): #Initialize car simulator initialize(): #Size of arena arenaSize := 40: establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. #Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ xStart,yStart,0,CARNORMAL]: CURRENTLOCATION := [xStart,yStart,0,CARNORMAL]: minLR := min(L1,R1): maxLR := max(L1,R1): #draw bottom and top walls setBackground([seq('[xStart+i, yStart+1],[xStart+i, yStart+leftRight]',i=0..bottomTop)], BARRIER): #draw left and right walls setBackground([seq('[xStart, yStart+i],[xStart+bottomTop, yStart+i]',i=1..leftRight)], BARRIER): drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration 226 11 More on proc and while turnFourTimesA := proc() local bt,angle,count; #Move forward while touching a wall, then #turn left #Initial scan angle is Pi/2 angle := Pi/2; #Initial count is zero. count := 0; while(count <4) do while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); angle := angle+Pi/2; count := count +1; end do; end proc: run(turnFourTimesA); carMovie(stateTable); 11.9 Example: a procedure that does a calculation instead oI controlling a car. 227 The programming Ior this solution is dramatically more succinct. II you can handle in stride the greater conceptual complexity oI putting one loop inside another loop, you will probably get your solution working Iaster, since there are Iewer characters to type, thereIore decreased chances oI making an entry error. 11.9Example: a procedure that does a calculation instead of controlling a car. Much oI technical programming has to do with the calculation oI mathematical Iormulae, visualizations, or numbers rather than control oI devices. Procedures can be used Ior such tasks. II you have a calculational script, in many cases it is easy to turn it into a procedure: 1. Rather than initializing script parameters at the start, remove those assignments and put the parameters into the sequence oI parameters oI the procedure. 2. The last thing calculated should be the result returned. In the example below, we return a list oI numbers, which allows us to communicate two results that the procedure has computed. One oI the advantages oI using a data structure such as a list is that it can be used as a "data container" Ior several results. #Given two sides of a right triangle, compute #the hypotenuse and the angle formed by it. triangleInfo := proc (side1, side2) local hypotenuse, angle, dAngle; #Use whatever values are provided when the #procedure is invoked 228 11 More on proc and while angle := arctan(side1,side2); dAngle := convert(angle,units,radians,degrees); hypotenuse := sqrt(side1^2+side2^2); #Return a list of the hypotenuse and the angle #(in degrees). [hypotenuse, dAngle]; end proc: Once we've deIined the Iunction, we can use it Ior several triangles: (11.6) (11.7) II we want one value or the other, we can use part extraction as explained in chapter 5. (11.8) (11.9) We note that while the procedure will calculate either with exact or Iloating point numbers, the Iloating point results are only approximations and may diIIer slightly Irom the correct answer. (11.10) (11.11) 11.10Troubleshooting small function definitions Function deIinitions with proc... end proc will exhibit typical "imbalance" error messages such as errors iI you Iorget to balance the typical things that occur in computer syntax: ( and ), iI and end iI, | and |, proc and end proc. II you do it in a code edit region, then in addition to printing out an error message, the cursor will pause over the Iirst place where the computer saw the imbalance. Troubleshooting problems with small function definitions
findPower := proc (x,tol) local i; i := 0; This Iunction loops to Iind last power oI x that is greater than tol. 11.10 Troubleshooting small Iunction deIinitions 229 term := x^i; while (term>tol) do term := x^i; Warning, premature end of input, use <Shift> + <Enter> to avoid this message. We note that there's no "end proc" to end the procedure deIinition. We edit the code region and execute it again. findPower := proc (x,tol) local i; i := 0; term := x^i; while (term>tol) do term := x^i; i := i+1; end proc; Error, reserved word `proc` unexpected AIter making that correction, we get a message that indicates that the proc wasn't expected. The cursor is positioned in the midst oI the "end proc" so we know that it's the last proc where things ran into problems.
We know that procedures must end with end proc, so removing it doesn't seem to be an option. But another cause oI end proc being unexpected is that something else was expected instead.
Looking harder, we realize, that we Iorgot the "end iI" to end the iI statement, too. findPower := proc (x,tol) local i; i := 0; term := x^i; while (term>tol) do term := x^i; i := i+1; end do; end proc; Warning, `term` is implicitly declared local to procedure `findPower` (11.12) (11.13) We get a warning message that term is not a local variable. Since we want it to be (it doesn't have a value outside oI the Iunction), we change the declaration. 230 11 More on proc and while findPower := proc (x,tol) local i,term; i := 0; term := x^i; while (term>tol) do term := x^i; i := i+1; end do; end proc; (11.14)
(11.15) This doesn't have any errors or warnings, but is it right? We need to test the Iunction. (11.16) (11.17)
The Iunction returns 23. But isn't greater than .1, so that can't be the last power greater than .1. findPower := proc (x,tol) local i,term; i := 0; term := x^i; while (term>tol) do term := x^i; i := i+1; end do; i -1; end proc; When we analyze what is going on, the value oI i computed in the loop is one too Iar. So we think we should really make the last value oI the Iunction one less. 11.10 Troubleshooting small Iunction deIinitions 231 (11.18)
(11.19) (11.20) (11.21)
Evidently our analysis is still oII. Looking harder, we see that we should change the order oI operations inside the loop, or we will go one too Iar. findPower := proc (x,tol) local i,term; i := 0; term := x^i; while (term>tol) do i := i+1; term := x^i; end do; i -1; end proc; (11.22)
(11.23) This works. But it took some analysis even beyond the point where we stopped getting error messages and warnings. 232 11 More on proc and while (11.24)
Troubleshooting problems with use of variables in procedures g := proc(a,n); local i, count; count := 0; while count<n do a := sqrt(a); #take multiple square roots count := count +1; end do; return a; end; Error, unexpected `local` declaration in procedure body This is a Iunction that's supposed to take n square roots oI a number: . There are several problems with it. The Iirst problem is that in order to declare a local variable, Maple insists that there be no extra semi-colon between the parameters (a,n) and the word "local". It should be proc(a,n) local i; .... g := proc(a,n) local i, count; count := 0; while count<n do a := sqrt(a); #take multiple square roots count := count +1; end do; return a; end; (11.25)
With this corrected, we get Maple to accept the deIinition, but it still doesn't work. The problem is that Iormal parameters can't be assigned to in Maple procedures. Formal parameters do not work the same as local variables.
The way to get the desired result is to set up a local variable and to initialize it with the value oI a beIore the loop starts. g := proc(a,n) local i, result,count; result := a; for i from 1 to n do result := sqrt(result); #take multiple square roots count := count +1; end do; return result; end; The Iunction works both Ior exact numbers and Iloating point numbers. 11.11 Troubleshooting local variable declarations 233 (11.26) (11.27) (11.28)
11.11Troubleshooting local variable declarations Warning messages from undeclared local variables
eApprox2 := proc(x, tol) local term,i; s := 1; term := 1; i := 1; while abs(term)>=tol do term := term*x/i; s := s+term; i := i+1; end do; return s; end proc: Warning, `s` is implicitly declared local to procedure `eApprox2` II you Iorget to declare a variable within a Iunction deIinition as a local variable, then Maple will do it Ior you but print out a warning. While this deIault action is almost always what is wanted, the warning is get you to think about whether you really wanted s to be a global variable (the same values used within the procedure and outside oI it) rather than local.
x := 0; while (x<=1.0) do print("Computed:",eApprox2(x, 10^(-5)),"Built- in", exp(x)); x := x + .1; end do: printf("s's value is: %a", s); We see that s's value within this script is not aIIected to what happened to s within eApprox2. s was automatically declared local to the eApprox2 procedure when it was deIined, even iI we didn't include it in the code.
By putting a colon at the end oI the "end do", we suppress the execution trace oI what's happening inside the loop. The print actions do cause output though. 234 11 More on proc and while s's value is: s
eApprox2 := proc(x, tol) local term,i,s; s := 1; term := 1; i := 1; while abs(term)>=tol do term := term*x/i; s := s+term; i := i+1; end do; return s; end proc: (11.30) (11.31) We can redeIine eApprox2. This doesn't change the meaning but it does get rid oI the warning messages.
Note that the computed result is based on x (the script version, not the local variable used inside eApprox2)'s last value Irom the previous computation in the worksheet. Since a the last computed value oI x Irom the while loop is 1.1, this is the value used in the computation here. 11.12 Troubleshooting while loops: loops that don't stop 235
11.12Troubleshooting while loops: loops that don't stop We've already reviewed some oI the basic problems with loops that come Irom Iorgetting to put in a end do or do, or putting too many in. These typically give some kind oI Error, message and were discussed here. More pernicious are loops which do not give error messages but either stop with the wrong answer, or do not stop. Such programming is called an infinite loop and they are usually something to avoid because the program will never come to a conclusion and let you regain interactive control oI the computer. You can tell that this is happening because you are either Ilooded with a lot oI output, or the status window in the lower leIt hand corner oI the worksheet says Evaluating.... but never seems to return to Readv. A runaway "infinite" loop
x := 3.0; while (x<10) do print("sin(x)", sin(x)); end do; 3.0 "sin(x)", 0.1411200081
"sin(x)", 0.1411200081
"sin(x)", 0.1411200081
"sin(x)", 0.1411200081
etc., etc. The problem with this loop is that it will never stop. The continuation condition is x10, which is true initially. Because the loop body never changes the value oI x, it will continue to be true Ior every successive repetition. Presumably the programmer made a mistake and Iorgot to put in lines oI code into the loop body that changed the value oI x and (with enough repetition) made it eventually grow to 10 or larger. In theory, you can stop long-running computations such as inIinite loops with the "red stop hand" Iound on the Maple tool bar. Clicking on the red stop hand will eventually stop the output, but not until aIter a long, long wait while all the output that resulted beIore you told the computer to stop looping, is printed. It typically takes a long time Ior it to print all the output Irom the repetitions, and you won't be able shut oII the printing with the red hand. So in practice, iI you have a runaway loop you oIten will have to Iorce-quit your Maple session and recover the most recent version oI your worksheet through File -~ Recent Backups-~ Recover Backup, as described in chapter 2. II you absolutely must execute a runaway loop again, Iirst change it to print very little so that it will stop beIore you get old waiting Ior it. Interrupting an evaluation with the "red stop hand" 236 11 More on proc and while AIter entering an equation to solve, we have realized that we really don't want to see millions oI roots listed, assuming that Maple can Iind them all. So we click on the red hand (circled in green). AIter a signiIicant pause, the message "computation interrupted" appears and we can enter another computation Ior Maple to perIorm. There is no result Irom the interrupted computation, so no result is displayed. The hand becomes gray instead oI red when execution is over.
This technique does not work well iI the long running computation prints a lot, as might occur in a runaway loop with a verbose execution trace. The CarSimulator package won't have the problem oI having the car take inIinite numbers oI moves by accident, because it has a built-in limit to the number oI steps that the car can take. However, you may discover that you have a "runaway car" who was only prevented Irom an inIinite loop by the built-in limits. It's still possible to write a car control program that doesn't end iI you include a loop that doesn't move the car (such as one that only prints, or assigns a variable a value). 11.13Summary of Chapter 11 General form of a Maple procedure definition with local variables function name : proc ( formal parameters ) local variables used within procedure; statements, 11.13 Summary oI Chapter 11 237 end proc; Notes 1. There is no semi-colon between the proc ( ) containing the Iormal parameters and the word local. II there are no local variables Ior the procedure, then you need to put in the semi-colon: proc ( formal parameters ) ; statements, .... 2. The opposite oI a "local variable" is a "global variable". We don't use them much in the Maple procedures we will be working with. You can read more about them iI you look up "global" in Maple on-line help. 3. You can't assign a value to a Iormal parameter in the statements oI the procedure. parameters are used only as a way oI providing input inIormation to the Iunction. The general form of the while statement while condition do loop bodv; end do; The condition is something that is either true or false. An error results iI it isn't. The condition is evaluated only once per repetition, at the start beIore any oI the code in the loop bodv is executed. II the condition is true, then the entire loop bodv is executed. II not, the repetition is Iinished and execution moves onto the next instruction aIter the end do.
The condition is evaluated at the start oI the loop iteration. It does not matter iI the condition changes in the middle oI the loop bodv; this won't terminate execution oI the loop until the execution reaches the end oI the loop bodv and thecondition looked at again beIore the start oI the next repetition oI the loop.
The continuation condition is can be a Iunction invocation that returns true or false, such as the isTouching or onTopOfSign Iunctions oI the CarSimulator package. It can also be an inequality such as x.1 or abs(y-z)~ tol. It always must be an expression that can be evaluated to be true or false. II the inequality is numeric such as x .1, variables in the condition such as x must have been assigned a numeric value earlier in the Maple session.
It is also possible to combine several conditions together using the operations and, or, and not(....).
true and false are reIerred to as Boolean values (aIter the British 19th century, George Boole -- http://www.gap-system.org/ ~history/Biographies/Boole.html Ior more inIormation). Functions that return Boolean values are reIerred to as Boolean functions, while and, or and not are reIerred to as Boolean operations. Stopping a never-ending (infinite) loop Stop the "red hand" icon on the Maple toolbar. II that doesn't work, then shut down the Maple session by killing the process (in Windows) or doing a Force Quit (in Macintosh). UnIortunately the latter will cause you to lose all the work you've done since last saving the worksheet, so it should be done only as a last resort. 238 11 More on proc and while 239 12More control: for and if 12.1Chapter Overview We introduce two more kinds oI control actions. for is a way oI doing looping. It doesn't do anything that we couldn't do with while, but it provides convenience -- less typing to get the same thing to happen. if allows us to tell the computer to decide between alternative courses oI action. 12.2for and indexed repetition for... from ... to ... do... end do In Chapter 11, we saw a car control problem where the car was supposed to turn Iour times. The way the solution was handled was by setting up a loop programmed with a while that used a variable called count. The variable was initialized to zero, and incremented by one each time through the loop. The condition oI the while was set to look at the value oI count and to stop the repetition when the count reached 4. This pattern -- using a counter variable to do things a set number oI times -- occurs so oIten in programming situations that most languages have notation to make setting up such loops convenient. General Iorm: Ior stepperJariable Irom initialJalue to finalJalue do loop bodv, end do; BeIore the loop starts, the stepperJariable is initialized to initialJalue. Then the loop runs as iI it were: while(stepperVariable IinalValue) do loop bodv, stepperJariable . stepperJariable 1, end do; II this is used within a proc....end, then the stepperJariable should be declared as a local variable. Here is shorter solution oI the "Iour turn" problem using for. The stepperJariable is i.
#Generate test problem #Turn left at the first 4 way intersection, go to target. #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator): StringTools[Randomize](); randomize(): #Pick a starting location for the car xStart := 5: yStart := 15: 240 12 More control: Ior and iI #Pick lengths of rectangle bottomTop := rand(4..10)(); leftRight := rand(4..10)(); #Initialize car simulator initialize(): #Size of arena arenaSize := 40: establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. #Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ xStart,yStart,0,CARNORMAL]: CURRENTLOCATION := [xStart,yStart,0,CARNORMAL]: minLR := min(L1,R1): maxLR := max(L1,R1): #draw bottom and top walls setBackground([seq('[xStart+i, yStart+1],[xStart+i, yStart+leftRight]',i=0..bottomTop)], BARRIER): #draw left and right walls setBackground([seq('[xStart, yStart+i],[xStart+bottomTop, yStart+i]',i=1..leftRight)], BARRIER): drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration 12.2 Ior and indexed repetition Ior... Irom ... to ... do... end do 241
turnFourTimesWithFor := proc() local bt,angle,i; #Move forward while touching a wall, then #turn left #Initial scan angle is Pi/2 angle := Pi/2; for i from 1 to 4 do while isTouching(angle,'bt') do move(1); end do; turn(Pi/2); move(1); angle := angle+Pi/2; #angle is now Pi end do; 242 12 More control: Ior and iI end proc: run(turnFourTimesWithFor); carMovie(stateTable); With a little analysis, we note that rather than incrementing angle each time, we can come up with the right angle by multiplying the current value oI the stepperJariable by , producing an even more succinct solution.
#Generate test problem #Turn left at the first 4 way intersection, go to target. #Reset all assignments in Maple so that they are forgotten restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator): 12.2 Ior and indexed repetition Ior... Irom ... to ... do... end do 243 StringTools[Randomize](); randomize(): #Pick a starting location for the car xStart := 5: yStart := 15: #Pick lengths of rectangle bottomTop := rand(4..10)(): leftRight := rand(4..10)(): #Initialize car simulator initialize(): #Size of arena arenaSize := 40: establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. #Set the starting location by resetting the state table and CURRENTLOCATION stateTable[0] := [ xStart,yStart,0,CARNORMAL]: CURRENTLOCATION := [xStart,yStart,0,CARNORMAL]: minLR := min(L1,R1): maxLR := max(L1,R1): #draw bottom and top walls setBackground([seq('[xStart+i, yStart+1],[xStart+i, yStart+leftRight]',i=0..bottomTop)], BARRIER): #draw left and right walls setBackground([seq('[xStart, yStart+i],[xStart+bottomTop, yStart+i]',i=1..leftRight)], BARRIER): drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration 244 12 More control: Ior and iI
turnFourTimesWithAngleFor := proc() local bt,i; #Do the following for each of four angles: for i from 1 to 4 do #Move forward while touching a wall, then while isTouching(Pi/2*i,'bt') do move(1); end do; #turn left and move forward one square turn(Pi/2); move(1); end do; end proc: run(turnFourTimesWithAngleFor); carMovie(stateTable); 12.3 variations on Ior: to ... do ... end do, Ior... Irom ... by ... to ... do ... end do 245 12.3variations on for: to ... do ... end do, for... from ... by ... to ... do ... end do II you just care about repetition without an index variable, you can use: to finalJalue do loop bodv, end do; This is not as Ilexible as the indexed repetition given in the previous section, but it will cause the loop body to be repeated finalJalue oI times. Programming by Bart Simpson to 5 do print("I will not burp in class."); 246 12 More control: Ior and iI end do; (12.5) You may have noticed in this example that the loop is not encapsulated in a procedure. Just like all other actions, you can include loops in scripts built without procedures. The advantage is that you don't have to go through the extra work oI including the procedure "header" or the declaration oI local variables. The downside oI procedure-less scripting is that it's harder to identiIy the scope oI the script, it is not given an easy- to-remember name, multiple invocation oI it requires more tedious editing oI the script, and lack oI encapsulation means that it is more diIIicult to make sure that you can move and successIully execute the script in another worksheet. II you want a stepper variable but you want to use steps other than 1, you can use: Ior stepperJariable Irom initialJalue to finalJalue by stepJalue do loop bodv, end do; For loop with a decrementing rather than incrementing steps print("x and sin(x)"); for x from 1 by -.3 to -1 do print( x, evalf(sqrt(x))); end do; (12.6)
Since the step size is -.3, then the finalJalue should be less than initialJalue oI 1. With a negative step value, the condition because while(x~-1) do... rather than while(x-1) do... which would cause the loop to stop immediately. 12.4 Choosing alternatives: iI...then...end iI, iI... then... else...end iI 247 12.4 Choosing alternatives: if...then...end if, if... then... else...end if The if statement allows a programmer to selectively execute code only iI a condition is true. if condition then code to executed iI the condition is true end if If-then-else-end if : one possible outcome
grade := 3.7: #This value will cause execution of the "then" code if (grade >= 3.5) then print("An excellent grade:", grade); end if; (12.7) II an "else" is added , then the computer will chose which oI two segments oI code it will execute, depending on whether the condition is true or Ialse. if condition then code to executed iI the condition is true else code to be executed iI the condition is Ialse end if If-then-else-end if : another possible outcome
grade := 3.2: #This value will cause execution of the "else" code if (grade >= 3.5) then print("An excellent grade", grade); else print("A grade:", grade); end if; (12.8)
Obviously, iI you are planning to do something once, you can probably just look at what's being computed and decide yourselI what to do. The value oI if is when you plan to use a script many times, or iI you need to make many conditional decisions within a loop in a single execution oI a script. If is helpIul because you won't have to stop to think about what happens each time. You can just set things up ahead oI time so that the right actions occur in either case. 248 12 More control: Ior and iI If-then-else-end if in a loop #Initialize a list with some numbers, some grade point # averages L := [3.6, 3.9, 2.1, 3.9, 2.1, 0.7, 1.3, 2.8, 3.6, 3.7, 2.9]; #Initialize some accumulation variables. We will use them #to count how many grades are 3.5 or above, and #how many are below. countHigh := 0; countLow := 0; #This goes first, before a loop, as a table header printf("Grades at least 3.5:\n"); #i steps through the possible index values for L. #Recall that nops(L) is the length of the list. for i from 1 to nops(L) do if (L[i] >= 3.5) then print( L[i]); countHigh := countHigh+1; #add one to the "high" counter else countLow := countLow+1; #add one to the "low" counter end if; end do: print("There were",countHigh,"grades at or above, and ", countLow, "grades below 3.5."); Grades at least 3.5: (12.9) A Iairly common occurrence is when the else alternative would speciIy to do nothing at all. Instead oI having an empty else branch, you should write the code without the else as if...then...end if. Example of If-then-end if
12.5 Coding situations with three or more cases using iI-then-eliI-eliI...else-end iI 249 In University oI West Dakota at Hoople, the Dean's list is determined by computing the average oI all student's grade point averages, and selecting those whose gpa is at least .5 point higher than the average.
restart; #unassign any previous values L := [3.6, 3.9, 2.1, 3.9, 2.1, 0.7, 1.3, 2.8, 3.6, 3.7, 3.8, 2.0]: deanCount := 0: #Compute the average for all students by #using sum to add up all the grades, and dividing by the #number of grades avg := sum(L[i],i=1..nops(L))/nops(L): #Print out table header. printf("Grade average of %d students is: %f.\n", nops(L), avg); printf("Grades at least one point above average (Dean's List):\n"); for i from 1 to nops(L) do if (L[i] >= (avg+1) ) then printf("%.2f\n", L[i]); deanCount := deanCount+1;
end if; end do: printf("\nThere were %d students making the Dean's List.",deanCount); Grade average of 12 students is: 2.791667. Grades at least one point above average (Dean's List): 3.90 3.90 3.80 There were 3 students making the Dean's List. 12.5 Coding situations with three or more cases using if- then-elif-elif...else-end if The if statements we have seen so Iar can be described as being useIul when: 1. The condition was used to select between one series, and doing nothing as the alternative. (if.. then...end if). 2. The condition was used to select between two alternative series oI actions (if...then..else..end if). Another situation that arises in practice is to select between three or more alternatives. This can be thought oI as "case by case" situation. if-then-elif-else-end if General form Notes if (condition 1) then statements separated bv , or . II condition 1 is true when the statement is executed, then the Iirst series oI statements is executed.
250 12 More control: Ior and iI elif (condition 2) then statements separated bv , or .
(more alternatives specified bv more elifs)
else statements separated bv , or .
end if Otherwise, iI condition 1 is not true but condition 2 is true, then the second series as executed.
Additional conditions will be checked iI none oI the previous ones turn out to be true. The sequence oI actions corresponding to the Iirst true condition will be executed.
II none oI the conditions are true, then last series oI statements are done.
The else section can be omitted. This is equivalent to doing nothing iI none oI the other conditions apply. The else portion oI the statement speciIies what is to be done iI none oI the previous cases apply. Example of If-then-elif-elif-...-else-end if #Initialize L to be a list of grades L := [3.6, 3.9, 0.9, 2.1, 3.9, 2.1, 0.7, 1.3, 2.8, 3.6, 3.7, 2.9, 1.3]; #Initialize counters foer the number of As, Bs, etc. (silently) countA := 0: countB := 0: countC := 0: countD := 0: countF := 0: #Process each element of the list, with the following #cases: #As (3.3 and above) #Bs (at or above 2.7 and below an A) #Cs (at or above 1.7 and #Ds (at or above 1.0 and below a C) #Fs (below 1.0). for i from 1 to nops(L) do x := L[i]; #Use "x" instead of typing L[i] several times if (x >= 3.3) then countA := countA +1; elif (x >=2.7) #this is tried only if first condition false then countB := countB +1; elif (x >=1.7) then countC := countC +1; elif (x>=1.0) then 12.6 A CarSimulator scenario solved with iI 251 countD := countD +1; else #we will be here only if everything else hasn't worked # so we know x<1.0. countF := countF +1; end if; end do: print(countA,"As", countB, "Bs", countC, "Cs", countD, "Ds", countF, "Fs"); (12.10) It is possible to include iI statements as one oI the actions inside another iI statement. This is useIul where a case may have subcases. We will discussion this situation in more detail in later chapters. 12.6A CarSimulator scenario solved with if The car passes over a numbered oI colored signs. When it detects a red sign, it should turn leIt. When it detects a yellow sign, it should turn right. Eventually it will encounter a purple sign and stop on it. Here is a sample scenario:
#Generate test problem #Turn left at red signs, #Turn right at yellow signs #Stop at target restart; #Look for packages in the current directory (".") as well as #built-in Maple library. libname := ".", libname; #Load CarSimulator package with(CarSimulator): StringTools[Randomize](); randomize(): #Starting location of the car is the default #Initialize car simulator initialize(): #Size of arena arenaSize := 40: establishBoundaries(arenaSize,arenaSize): #draw a sandbox for the car to roam around in. Coordinates range from [0,0] to [arenaSize, arenaSize]. numTurns := rand(4..14)(): lastLocX := 0: 252 12 More control: Ior and iI lastLocY := 0: for i from 1 to numTurns do distance := rand(2..5)(); if i mod 2 = 1 then #move horiz nextLocX := lastLocX +distance; nextLocY := lastLocY; setBackground([nextLocX, nextLocY], REDSIGN); else #move vertical nextLocX := lastLocX; nextLocY := lastLocY + distance; setBackground([nextLocX, nextLocY], YELLOWSIGN); end if; lastLocX := nextLocX; lastLocY := nextLocY; end do: distance := rand(2..5)(); if numTurns+1 mod 2 = 1 then #move horiz nextLocX := lastLocX +distance; nextLocY := lastLocY; setBackground([nextLocX, nextLocY], PURPLESIGN); else #move vertical nextLocX := lastLocX; nextLocY := lastLocY + distance; setBackground([nextLocX, nextLocY], PURPLESIGN); end if; drawBackground(): #Create a plot of the wall and the target for later use, but don't display it yet carMovie(stateTable); #Show initial configuration 12.6 A CarSimulator scenario solved with iI 253
We use the onTopOfSign operation oI the CarSimulator (described in the on-line documentation, which you should look at iI you want to understand what the diIIerence is between PURPLESIGN and PURPLESIGNHIT, Ior example). turnRedYellow := proc(); #No local variables needed in this procedure #Move while you're not on a purple sign while not(onTopOfSign(PURPLESIGNHIT)) do #turn right if you're on a red sign if onTopOfSign(REDSIGNHIT) then turn(Pi/2); 254 12 More control: Ior and iI #turn left if you're on a yellow sign elif onTopOfSign(YELLOWSIGNHIT) then turn(-Pi/2); end if; move(1); #move forward regardless of whether #you've turned. end do; end proc:
run(turnRedYellow); carMovie(stateTable); 12.7 For the curious: comparing control statements in conventional programming languages Almost all conventional programming languages (C, Mathematica, C#, Java, Matlab, Maple, C, NXT, Python, Perl, Visual Basic, etc.) have the "loop" idea and the "selection/case" ideas in them. The main diIIerence in how they speciIy them through the use oI diIIerent words or symbols. Java Ior example, uses and } rather than "then" or "end iI" to delimit the begin and end oI segments oI actions. Portion of a 1ava program with a conditional int countThree, countSubThree; 12.7 For the curious: comparing control statements in conventional programming languages 255 int [] L= {1,5,9,2,6,7,-2,1,7}; // Set up counters countThree=0; countSubThree=0; // Loop through L counting how many are above three for (int i=0; i<L.length; i++) { if (L[i]>3) \011{ countThree++;} else \011{countSubThree++;} }; System.out.println("three and above:"+countThree+ \011 " below three: "+ countSubThree);
While this portion oI the Java program is quite intelligible to someone who is more experienced in Maple, a Iull program to do this would require additional statements that we don't should here. Note that the printing statement println uses "" not Ior numerical addition but to combine the output into a single string that println can handle. Getting used to these language-speciIic idiosyncrasies are part oI the overhead oI working with more than one tool on a computer. The Matlab program Iollow with a loop and a conditional may look similar to a Maple program, although it uses diIIerent Iunctions to extract size ("size" rather than "nops") and there is diIIerent syntax (no do, just "end", "" instead oI from and ":" instead oI to. Portion of a Matlab M-file with a loop and a conditional %Program to count how many elements of a vector/list are greater than and less %than three countThree=0; countSubThree=0; L=[1,5,9,2,6,7,-2,1,7]; [r,c]=size(L); %Loop for i from 1 to c, where c is the number of items in L (length of L) for i=1:c if L(i)>3 countThree=countThree+1; else countSubThree=countSubThree+1; end; 256 12 More control: Ior and iI end; %Use formatted printing to print out things. sprintf('Three and Above: %d, Below three: %d', [countThree, countSubThree])
There may be other ways oI doing the same task in a language that may be easier in that particular language. For example, summing together numbers in Java involve writing a loop that gathers the sum oI the numbers, whereas in Maple one could use sum and get the job done in one line. C, Java and C have a "?" operator which one could use to write the if oI the above example more succinctly even though it would work the same as the kind we have worked about. No language will ever be "the most convenient" Ior all tasks, which is one oI the reasons why so many languages endure. Regardless oI what you think about the way other languages handle loops and conditional execution, learning how to do it in Maple transIers to most other languages you may choose to work with in the Iuture. 12.8 Troubleshooting if statements While, for, and if statements require you have to have words such as "while" "do", "iI", "else", etc. written in exactly the right sequence or else the language processor will reject them. Sixty years oI advances in programming language technology haven't made the situation Ior programmers much easier. It's still necessary to learn how to do it correctly, and how to troubleshoot your way out oI problems when you make a mistake. You can use the Iact that the computer will let you experiment as much as you want to help you learn. Now that you have learned how to enter code into worksheets and code edit regions, you can start oII by learning new syntax by exactly reproducing an example that contains output as well as input, and seeing whether you can get the same results. Next, you can try modiIying the examples to do slightly diIIerent things, and seeing whether you are successIul at the modiIications. Finally, you can try to enter something oI your own devising, Irom scratch. Getting expert help can be a useIul way oI quickly seeing how to notice and Iix the basics. However, the point Irom getting such help is not to only to get your mistake Iixed, but also to learn Irom the experience so that you can avoid and/or recognize how to Iix similar things in the Iuture on your own. Examples of Errors with if statements Example Commentary
x := 3; countThree := 0; countSubThree := 0; if x>3 then countThree := countThree +1; else countSubThree := countSubThree +1; end if; printf("three and above:%d, below three: %d", No missing pieces here. 12.8 Troubleshooting iI statements 257 countThree, countSubThree); three and above:0, below three: 1
x := 3; countThree := 0; countSubThree := 0; if x>3 countThree := countThree +1; else countSubThree := countSubThree +1; end if; printf("three and above:%d, below three: %d", countThree, countSubThree); Error, missing operator or `;`
In this example, we Iorgot to put in the word "then". AIter the error, the cursor is positioned in the midst oI the line aIter the "iI", which is the Iirst time that Maple's input processor notices that there's something wrong. To handle this error, one looks backwards Irom the position oI the cursor to see iI there's anything missing. Admittedly there's not a lot oI inIormation given that the cause is a missing then, but this is Iairly typical in working with programming languages. You'll get an indication that there's something wrong, and the point at which the wrongness was Iirst noticed, but you won't be able to depend on the error message to tell you exact what was wrong. II computer technology could do that reliably, systems would just Iix the errors automatically. But doing that well seems to require artiIicial intelligence beyond present conventional technology.
x := 3; countThree := 0; countSubThree := 0;
We Iorgot to end the statement with end iI (or Ii). 258 12 More control: Ior and iI if x>3 then countThree := countThree +1; else countSubThree := countSubThree +1; printf("three and above:%d, below three: %d", countThree, countSubThree); Warning, premature end of input, use <Shift> + <Enter> to avoid this message.
x := 3; countThree := 0; countSubThree := 0; if x>3 then countThree := countThree +1; else countSubThree := countSubThree +1; end do; printf("three and above:%d, below three: %d", countThree, countSubThree); Error, reserved word `do` unexpected
We said "end do" rather than "end iI".
x := 3; countThree := 0; countSubThree := 0; if x>3 then countThree := countThree +1; Actually, this is not a mistake. Evidently "end iI" and "end" are acceptable here. "Ii" is another way oI ending an if statement. 12.8 Troubleshooting iI statements 259 else countSubThree := countSubThree +1; end; printf("three and above:%d, below three: %d", countThree, countSubThree); three and above:0, below three: 1
x := 3; countThree := 0; countSubThree := 0; if x>3 then countThree := countThree +1; else countSubThree := countSubThree +1; end if printf("three and above:%d, below three: %d", countThree, countSubThree); Error, missing operator or `;`
We get the same error message as in the second item in this example. However, this time the problem is that we leIt oII the semi-colon aIter the end iI. We need it iI there's an instruction aIter the iI statement in the script.
Programmers need to the consider that there could be more than one kind oI mistake that would provoke an error message. This kind oI situation can be encountered with almost any sort oI programming system (e.g. C, Matlab, Java, etc.) due the limitations oI conventional language-processing technology.
x := 3; countThree := 0; countSubThree := 0; IF x>3 THEN countThree := countThree +1; ELSE countSubThree := countSubThree +1; END IF;
The mistake here is that "IF" does not mean the same thing as "iI" to Maple -- case matters. Executing this script gives an error message with the cursor positioned right aIter the IF. The error message is saying that Maple doesn't know what to do with the IF. It is not particularly inIormative about the 260 12 More control: Ior and iI printf("three and above:%d, below three: %d", countThree, countSubThree); Error, missing operator or `;`
cause. You could discover the cause by comparing what is done with examples that are known to work which all use "iI" rather than "IF". 12.9Summary of Chapter 12 General form of for statement Example Ior stepperJariable Irom initialJalue to finalJalue do loop bodv, end do;
for angle from 5.0 to 10.0 by .5 do x := convert(angle, units, degrees, radians); print("Cosecant of ", angle, " degrees is", csc(x)); end do: (12.20) General forms of if...then..else...end if Example
if condition then #print out a message if a sin of a multiple of Pi/4 is 1 or -1. for i from 1 to 10 do if abs(sin(i*Pi/4)) = 1 then 12.9 Summary oI Chapter 12 261 code to executed iI the condition is true end if
print(i,"sin(",i*Pi/4," ) is ", sin(i*Pi/4)); #i*Pi/4 automatically reduced to simplest terms in output end if; end do; (12.21) if condition then code to executed iI the condition is true else code to be executed iI the condition is Ialse end if
grade := 3.2: #This value will cause execution of the "else" code if (grade >= 3.5) then print("An excellent grade", grade); else print("A grade:", grade); end if; (12.22)
if (condition 1) then statements separated bv , or . elif (condition 2) then statements separated bv , or .
(more alternatives specified bv more elifs)
else statements separated bv , or .
end if
for i from 1 to 10 do if i=1 then print("i is one"); elif isprime(i) #built-in primality testing function #Returns true if its argument is a prime number #See on-line documentation for isprime. then print (i, "is prime"); elif i mod 2 = 0 #test for divisibility by two #See on-line documention for "mod" then print(i, "is even"); else 262 12 More control: Ior and iI print(i, "is neither prime nor even nor one"); end if; end do; (12.23) 263 13Looking inside execution of a procedure or script 13.1Chapter Overview In this chapter, we show ways oI providing more printed output while a script or procedure is running. printf and sprintf provide formatted printing -- Iine control oI exactly how numbers, Iormulas, and other results appear when they are printed. We revisit the use oI colons as a way oI suppressing execution trace output Irom loops. Finally, we introduce the trace operation as a way oI causing deeper amounts oI execution tracing to occur, allowing programmers to view the internal operation oI user-deIined procedures. 13.2More on printing: print, printf and sprintf In Chapter 10, we introduced print that prints the value oI things out during execution oI a script. A synopsis oI print is that it is a Iunction that takes a sequence oI values as arguments, and returns NULL as a result. Its use is in its side effect -- it causes the sequence oI values to be displayed in the worksheet in two dimensional Iormat. Use of print Example Commentary
(13.1)
(13.2) We set up a list oI values. L has all Iloating-point values because the "10.0" in the denominator causes all computations to be done using limited- precision arithmetic. The display oI the value oI L is suppressed because we ended the assignment with a colon.
print prints out the sequence oI values given to it as arguments. You can give any number oI items in the sequence. The commas separating the string and the number are Irom the sequence. Note that the result is not displayed because the line ends with a colon. printf is a similar Iunction, but it provides the programmer more precise control over the Iormat oI the output. The Iirst item in the sequence oI parameters to printf is a format string: a string that contains ordinary words plus special Iormat codes that begin with . The table below summarizes common Iormat codes. Common formatting codes for printf and sprintf Format code Example Explanation a Algebraic format. Works Ior any type oI value. The value is printed out in a Iormat suitable Ior textual input. 264 13 Looking inside execution oI a procedure or script The answer is: x = x^2+1
f w.df The answer is : 0.009095 0.00910
2432902008176640000.00000 0.750000
The answer is: Error, (in IprintI) number expected Ior Iloating point Iormat
Fixed format Ior Iloating point numbers. w and d are optional. II given, w describes the number oI columns Ior the entire number, and d the number oI columns Ior the number aIter the decimal point.
Values will be converted to Iloats where possible. e w.de
9.095277e-03 9.09528e-03 3.628800e+06 ScientiIic Iormat Ior Iloating point numbers. wand d are optional. II given, w describes the number oI columns Ior the entire number, and d the number oI columns Ior the number aIter the decimal point. II w is wider than the number oI digits required, then it is Iilled out with leading white space.
Values will be converted to Iloats where possible. 13.2 More on printing: print, printI and sprintI 265 7.500000e-01 (13.4) 2.43290e+18 7.500000e-01
The answer is: Error, (in IprintI) number expected Ior Iloating point Iormat
d 2432902008176640000
Error, (in IprintI) integer expected Ior integer Iormat
Error, (in IprintI) integer expected Ior integer Iormat
(13.6) 3
Format Ior integers.
This Iormat rejects any value that is not oI integer type. The built-in whattvpe Iunction can provide guidance about what is and what isn't going to work, iI you aren't sure.
266 13 Looking inside execution oI a procedure or script (13.7)
s The color is DodgerBlue.
Format Ior strings. \n One two, buckle my shoe. 3, 4, shut the door. Causes a line break between preceding and succeeding parts oI the output. \t 1,\0112,\011buckle my shoe. 3\0114,\011shut the door.
Causes next output to appear starting at the next columnar (tab) position. The on-line documentation Ior printf describes all Iormat codes comprehensively. Some oI them allow Ior quite intricate eIIects such as right or leIt justiIication, padding with leading or trailing zeroes, etc. printf can allow computed inIormation to be printed quite expressively. However, the Iormat codes will give error messages iI you supply a value that can't Iit into the Iormat. Use of printf Example Commentary We set up a list oI values as in the previous example. The last element of the list is 0.800000.
The Iirst argument to printI is a string describing how to Iormat the rest oI the values. The string contains Iormat codes describing where to insert the values oI the later arguments into the message described in the string. In this example, there is one Iormat code I, Ior printing numbers in conventional decimal point notation. Since printI joins together the message and the value together into a single message without a sequence into a single result, what is printed is without commas. 13.2 More on printing: print, printI and sprintI 267 There are 4 elements in this list. The largest is 9.048374e-01.
Additional printI codes are "d" (Ior integer values), and "e" (Ior Iloating point numbers in scientiIic notation). The Iormat code \n causes the next output to occur on the next line. L has 4 elements. The largest is 9.048374e-01.
Note that a printI statement does not automatically cause the output on a new line. Thus, several printI statements executed together as these are will have all the output on a single line. There are 4.000000 elements in this list. The largest is Error, (in IprintI) integer expected Ior integer Iormat
II you attempt to use I Iormat on an integer, or d Iormat on a number that is not an integer, you will get incorrect values (with no warning that they are incorrect), or possibly an error message. Let the user beware; the computer isn't going to necessary save you Irom making a mistake. Error, (in IprintI) number expected Ior Iloating point Iormat
You can't print a list oI Iloating point numbers using just I Iormat. [.9048374180, .8187307531, .7408182207, 4/5] The a Iormat will handle arbitrary numerical or non-numeric values. The value being printed out is a list, which is a "non-numeric value" because it isn't a single number. However, the output uses the textual Iormat rather than the "pretty" Iormat used by print. sprintf is like printf in that its Iirst argument is a string with Iormat codes, and the rest oI its arguments are values to be Iormatted. However, unlike printf it does not print (display) any inIormation. It returns a string which is the Iormatted inIormation instead. This is useIul in situations where Iunctions need Iormatted inIormation, such as titles or labels oI plots. Use of sprintf Commentary (13.9) (13.10)
We set up a list oI data points. Using sprintI, we create a string. The d Iormat is used to insert the number oI points into the message. 268 13 Looking inside execution oI a procedure or script
We need the string to put a title onto our pointplot. You can read more about the title argument to pointplot by entering plot,options in Maple's on- line help.
The advantage oI using sprintf is in re-use. II we want to plot a diIIerent set oI points, we can change the line assigning L (and the plot line oI x coordinates), but we don't have to alter the sprintI since it will automatically use the right value corresponding to the length oI the list. print and printf are oIten included in procedures being debugged by programmers. This is to make the execution trace more intelligible which oIten allows the programmer to more quickly Iind where a computation is going awry. "Commenting out": The idea with diagnostic print/printI output is that it is put in to Iind the cause oI a problem, and then taken out aIter a programmer thinks that they've Iound and Iixed the problem. However, it is oIten the case that there is more than one problem in the program. OIten times, aIter Iurther work Iixing multiple problems, the need Ior the same diagnostic output as beIore returns. For this reason, rather than deleting printing statements (and then needing to type them in again), the programmer puts a comments symbol # in Iront oI the printing operation. This deactivates the printing until the # is removed. It's a lot easier to delete and add a comment sign than it is to retype a printing statement. 13.3For the curious: why printf is so cryptic The Iormat codes Ior printf are a "programming language within a programming language" in that they describe in abbreviated Iorm how the computer should output values. The style used Ior Iormat codes is very much unlike the rest oI Maple, in that brevity rather than readability seems to be the criterion used to design this portion oI the language. A language Ior science and engineering popular starting in the middle oI the twentieth century was Fortran, which had Iormatting that was similar in approach but was much diIIerent in syntax. Given your knowledge oI Maple (and English), the intent oI the program is Iairly obvious: it will print There were 3 values, and the answer was 4.7. A Fortran program that demonstrates formatted printing n = 3 x = 4.7 print (*,35) n,x 13.4 Suppressing execution trace output Irom loops 269 35 format('There were',i2,' values, and the answer was',f5.1, '.') stop end The design oI printf can be explained by the Iact that Maple's printf is a close imitation oI the printf Iound in the programming language C (popular with many programmers at the time Maple was invented in the '80s, and still popular among computer engineers and scientists doing device programming). Matlab, being invented in the same era, also a sprintf Iunction oI highly similar design. Imitation makes it easier to transIer programming skill Irom one language to another. Inventors oI programming languages will tend to imitate unless they have a goal or insight that justiIies a diIIerence. Programming languages designed by skillIul designers do not introduce arbitrary diIIerences without a good cause. When you notice similarities between languages, take it as a recognition that many people liked that style oI doing things, across many diIIerent kinds oI programmers and kinds oI problems. When you notice a diIIerence between languages, you should explore the reasons why the designers made diIIerent choices. Usually there is a problem or issue that the designer is trying to handle better by being diIIerent Irom the rest oI the pack. Matlab script for plotting a few points, in blue
This probably isn't the only way, or the shortest way, of producing the title in Matlab, but we use it to illustrate that knowledge of formatting codes is one of the things that transfers between languages. Matlab also has a sprintf function. About the only formatting features that it (as of February, 2012) lacks is a a format code to make conversion of formulas convenient. Programming language Ieatures Ieatures that work across tens oI thousands oI programmers and programs are usually motivated by signiIicant design rationales. The design oI most programming languages is nowadays inIormed by what worked well or didn't work well in the past. 13.4Suppressing execution trace output from loops We mentioned it in Chapter 12 beIore, but do so again as our use oI loops grows: putting a colon (:) rather than a semi-colon (;) aIter the end do oI a while or for loop suppresses the execution trace output normally produced by the loop. II you want to see particular results Irom within the loop, use print or printf, which are not suppressed by the use oI colons. Accumulation of two results in the same loop; suppression of output n := 5; result := 0; result2 := 1; for i to n do What the execution trace oI this loop looks like without output suppression. Since the loop computes two things per repetition, 270 13 Looking inside execution oI a procedure or script result := result+i; result2 := result2*i^2; end do; printf("The sum of the numbers from 1 to %d is: %d.\n", n, result); printf("The product of squares i^2 from i=1 to %d is %d.\n",n,result2); The sum of the numbers from 1 to 5 is: 15. The product of squares i^2 from i=1 to 5 is 14400.
and repeats 10 times, there are 10 lines oI output to look at. Imagine what would happen iI there n were 100. n := 10; result := 0; result2 := 1; for i to n do result := result+i; result2 := result2*i^2; end do: printf("The sum of the numbers from 1 to %d is: %d.\n", n, result); We suppressed output Irom the execution trace by placing a colon at the end do, which suppresses the execution trace oI everything in the loop body. This is something to do aIter you have gotten the loop to work correctly. 13.5 Looking inside oI procedure invocations (Iunction calls) with trace 271 printf("The product of squares i^2 from i=1 to %d is %d.\n",n,result2); The sum of the numbers from 1 to 10 is: 55. The product of squares i^2 from i=1 to 10 is 13168189440000. n := 10; result := 0; result2 := 1; for i to n do result := result+i; result2 := result2*i^2; printf("i is: %2d, result2 is: %4.2e \n",i,result2); end do: printf("The sum of the numbers from 1 to %d is: %d.\n", n, result); printf("The product of squares i^2 from i=1 to %d is %d.\n",n,result2); i is: 1, result2 is: 1.00e+00 i is: 2, result2 is: 4.00e+00 i is: 3, result2 is: 3.60e+01 i is: 4, result2 is: 5.76e+02 i is: 5, result2 is: 1.44e+04 i is: 6, result2 is: 5.18e+05 i is: 7, result2 is: 2.54e+07 i is: 8, result2 is: 1.63e+09 i is: 9, result2 is: 1.32e+11 i is: 10, result2 is: 1.32e+13 The sum of the numbers from 1 to 10 is: 55. The product of squares i^2 from i=1 to 10 is 13168189440000. We can see a trace oI just the result2 values by including a printf statement. This gives us the opportunity to include other inIormation that might help understand the execution trace. Note that we are using a Iormat code Ior i that makes its output always appear in two columns, which lines up the output that is easier to read. You can read about this in the on-line help Ior printI. 13.5Looking inside of procedure invocations (function calls) with trace II we have a script where a procedure is invoked, then the execution trace normally only displays the result oI the procedure. However iI there is a programming error in a procedure we've written, we won't see the execution trace oI the actions within the procedure. 272 13 Looking inside execution oI a procedure or script Maple provides another operation, trace, which will turn on the execution trace within a procedure. untrace is a way to turn oII tracing once we no longer need it. Or write a code edit region that begins with restart, which will also cause Maple to stop tracing (as well as Iorget about the state oI everything else that had happened in the session. By tracing the procedure we see the execution trace oI each action during the procedure. It is easier to see which line is going wrong with the trace on. AIter you are Iinished tracing, you can stop the tracing by doing a untrace('procedure name),. II your code edit region includes both the procedure deIinition and its invocation, then you can also turn oII tracing by putting a restart as the Iirst line oI the region. Tracing and untracing a function Problem: We give a team oI two students a series oI 4 individual tests. We wish to award them a point total that's the sum oI the best score Irom each test. For example, iI one student had scores oI 1,3,5, and 10, and the other student had scores oI 0, 4, 6 and 7, then the sum would be max(1,0) max(3,4) max(5,6) max(10,7) 21. Write a procedure that takes two lists oI scores produces the desired sum as a result.
maxSum := proc(xdata, ydata) local s,i, n; #Loop over the 1st, 2nd, etc. value of the lists for i from 1 to n do #Compare them and add the larger to s. if xdata[i]>ydata[i] then s := s + xdata[i]; else s := s + ydata[i]; end if; end do; return s; end proc;
(13.14) We deIine the procedure. (13.15) (13.16) We try it out. We get error messages. Bummer. But what is causing the problem? 13.5 Looking inside oI procedure invocations (Iunction calls) with trace 273 Error, (in maxSum) Iinal value in Ior loop must be numeric or character
(13.17) --~ enter maxSum, args |1, 3, 5, 10|, |0, 4, 6, 7| -- ERROR in maxSum (now at top level) Iinal value in Ior loop must be numeric or character} Error, (in maxSum) Iinal value in Ior loop must be numeric or character
Tracing the procedure and running the test again shows the execution trace oI the procedure. It seems to being with the inIormation we expect Irom L1 and L2. However, it immediately gives an error, which means that the Iirst line oI action -- "Ior i Irom 1 to n do..." must be causing the error. The trace doesn't tell us how to diagnose the cause or the cure -- we have to apply our knowledge oI what Ior loops want. We consult examples oI loops -- we seem to using the right syntax. But the message says that "Iinal value in Ior loop must be numeric or character". The Iinal value in this case is n -- and that causes us to realize that we never assigned n a value. n does not have a numeric or character value. The way to Iix this mistake is to decide how we are going to give n the right value, which is the number oI items in the list. maxSum := proc(xdata, ydata) local s,i, n; n := nops(xdata); #Loop over the 1st, 2nd, etc. value of the lists for i from 1 to n do #Compare them and add the larger to s. if xdata[i]>ydata[i] then s := s + xdata[i]; else s := s + ydata[i]; end if; end do; return s; end proc;
274 13 Looking inside execution oI a procedure or script (13.19) (13.20) (13.21) --~ enter maxSum, args |1, 3, 5, 10|, |0, 4, 6, 7| -- exit maxSum (now at top level) s21} (13.22)
RedeIining maxSum again has removed the trace. We need to invoke trace again.
Once we do so, we see the execution trace. We see that the Iirst operation "n: ..." results in 4, which is correct since that's the length oI L1 (what was given as the Iirst argument xdata).
The next operation would be one oI the s : s xdata|i| or s : s ydata|i|. We expect this to be an accumulation oI the maximum values. However we are getting "s1" rather than just "1".
This causes us to realize that we have Iorgotten to initialize s. maxSum := proc(xdata, ydata) local s,i, n; n := nops(xdata); s := 0; #Initialize accumulation variable to zero. #Loop over the 1st, 2nd, etc. value of the lists for i from 1 to n do #Compare them and add the larger to s. if xdata[i]>ydata[i] We edit the code edit region and execute it again, redeIining the procedure. 13.5 Looking inside oI procedure invocations (Iunction calls) with trace 275 then s := s + xdata[i]; else s := s + ydata[i]; end if; end do; return s; #Return accumulated sum as the result. end proc; (13.23) (13.24) --~ enter maxSum, args |1, 3, 5, 10|, |0, 4, 6, 7| -- exit maxSum (now at top level) 21} (13.25)
We have to trace the procedure again since the redeIinition oI maxSum wipes out Maple's notes that the procedure was traced. It seems to work better now. (13.26) To untrace, we have to put the name oI the procedure in single quotes.
276 13 Looking inside execution oI a procedure or script (13.27)
Once we untrace, we can use the Iunction without seeing the execution trace. Recall that you can also look at the value oI variables after execution is ended by looking at the Variables panel oI the Maple window, as described in Chapter 4. 13.6 Summary of Chapter 13 printf, sprintf L has 4 elements. The largest is 9.048374e-01.
The Iirst argument to printI is a string containing Iormat codes speciIying how the values oI the subsequent arguments should appear. Common Iormats are d, I, e, s. There are large number oI modiIiers. \n is the Iormat code to cause next output to appear on a diIIerent line. (13.28) (13.29) sprintI is good Ior manuIacturing plot titles, among other things. 13.6 Summary oI Chapter 13 277
Suppressing output in loops Ending a while or for loop with a end do: rather than end do; will suppress the execution trace oI all the activity within that loop. There is no need to end each line within with a colon. Tracing procedures trace(maxSum); Turns on execution tracing oI the named procedure. untrace('maxSum'); Turns oII execution tracing oI the procedure. Name oI procedure must be enclosed in apostrophes (single quotes). 278 13 Looking inside execution oI a procedure or script 279 14Tables and other data structures 14.1Chapter Overview This brieI chapter introduces Maple tables. Tables are another way in Maple to store multiple values in a single "data container". Unlike Maple lists, Maple tables are mutable, which means that you can add or change data in them without having to copy anything. We revisit another data structure, the sequence and show how it can be used to do multiple simultaneous assignment, and to return multiple results from a procedure. 14.2A review of Maple data structures and properties The value oI computers in technical work comes not only Irom doing long calculations conveniently, but being able to do thousands or millions oI shorter computations quickly. Loops (for and while) are one way to harness this power without making the programming very tedious. Another need is a way to store lots oI data. We've already seen lists, sequences, and sets as general-purpose containers. Maple also has specialized containers: ranges, equations, and expressions. Let's review the data containers we've seen and used in Maple so Iar. Each kind oI container has a diIIerent syntax to create it, and to access its parts. Variables can be assigned as their value their whole container. Some Maple Iunctions use the whole container, while in other cases you use "parts access" to use particular items within the container. One common aspect oI these data containers is that they are immutable: once you've created them, you can't change them, you can only access (Iind out the value oI) their value. In order to "change" a list or expression, Ior example, what you have to do is to create a new list/expression with the changes in it, and assign it to the same variable as had the old list. Type of container Examples How to create it How to access a part of it Operations that can be performed with container Ways of changing data container after it's been created Math expression a b c exp(-b*x/3) sqrt(32)- y`2 Type it in using an arithmetic operation or mathematical Iunction op(i, expr) gets the i-th piece oI the expression Arithmetic and math Iunctions: , -, *, `, /, sqrt, !, etc., nops(expr) tells you the number oI terms in the expression. Can't do it. Can only create a new container with edited content. Range 1..10 as in plot(x`2, x 1..10) Type it in using a ".." op(1, r) gets the low end oI the range. op(2,r) gets the high end None other than access Iunctions, but many Iunctions use ranges as one oI their parameters. Can't do it. Equation 2*x-35 as in solve(2*x-35,x) Type it in using a "" rhs(eqn), lhs(eqn) gets the right and leIt hand sides oI the equation solve, Isolve, plot, etc. although usually other arguments are necessary Can't do it. List |1.1, 2.3, 5.5|
| | #empty list Type in items separated by commas, enclosed by square brackets. L|i| gets the i-th item Irom the list. II i is negative, counting starts Irom the end.
nops tells you the number oI items in the list Can't do it. 280 14 Tables and other data structures Type of container Examples How to create it How to access a part of it Operations that can be performed with container Ways of changing data container after it's been created L|i..j| gets a list oI the ith through fth items. Plot structures Result oI plot(x`2, x1..10) As a result oI a plot or display operation. Typically, you don't want to, you just want to print it. op does work on plot structures (see structure, plot in Maple on-line help) printing plots is the main thing that you want to do. You can also operate on them with the plots|display| operation. Can't do it. Sequences NULL #empty sequence Type in items, separated by commas. L|i| gets the i-th item Irom the list. II i is negative, counting starts Irom the end.
L|i..j| gets a list oI the ith through fth items. All Maple Iunctions accept sequences, although not all oI them work with sequences that are the wrong length or provide the wrong kinds oI values. Can't do it. Set 1.1, 2.3, 5.5}
} #empty set Type it in: items separated by commas, enclosed by curly brackets. S|i| gets the i-th item Irom the set.
S|i..j| gets a set oI the ith through fth items. nops tells you the number oI items in the list
union, intersect, minus, perIorm set operations Can't do it. 14.3 Tables In this section, we introduce another kind oI data structure, tables. A table is a structure where each element is accessed using a value called a kev or index. Individual elements oI the table can be assigned, in any order. Individual elements can be accessed using the index notation, e.g t|2| to get the element oI the table t whose access key is 2. This is similar to how lists worked, where L|2| Ior a list L was an expression whose value was the 2nd element oI the list L. The kev can be any valid Maple value, not necessarily an integer (although they oIten are). Tables can add elements over time with additional assignments. Tables are useIul in situations where we will be adding items to the data structure Irequently, but we don't know in advance how many entries we will ultimately have. They will be more eIIicient to use than lists or sets in that kind oI situation. In Iuture chapters we will also see ways to exploit the other useIul property oI tables, where it is more convenient to have non-integer values Ior access keys. Example Demonstration of tables 14.3 Tables 281 Example (14.1)
This creates a table named T. Initially there are no items in the table. Whatever previous value T may have had is Iorgotten. (14.2)
Through assignment we create a table entry Ior T|1|. (14.3)
Through assignment we create a table entry Ior T|2|. (14.4)
Through assignment we create a table entry Ior T|4|. The value oI this entry depends on the values oI T|1| and T|2|. (14.5)
We reassign the value oI T|2|, overwriting the previous value. (14.6)
Expressions mentioning assigned elements oI the table will use the assigned value. II that element oI the table does not have an assigned value, it remains just as a symbol. (14.7)
The indices Iunction will return a sequence oI the access keys Ior the table. Each access key is enclosed in brackets so that you can tell where one key stops and the next begins. (14.8)
The entries Iunction will return a sequence oI values stored in the table. The sequence is generally listed in the same order that the indices Iunction lists access keys. (14.9)
This is the way to tell how many items are in a table at any time. Note that nops(indices(T)) does not work because indices produces a sequence oI items, so that nops would typically be given several arguments instead oI the one that it expects. 282 14 Tables and other data structures Example (14.10)
The convert command can be used to put all the entries oI a table into one list.
(14.11) (14.12) (14.13)
The indices oI a table can also be letters. Here we assign a value to the index T|x|. (14.14)
This is the way to remove an entry Irom the table -- putting quotes (', not backquotes `) around the item being removed. This is also the way unassignment oI values were done Ior ordinary variables in section 4.2. (14.15) (14.16)
AIter removing the item, we see Iewer items in the table. We can create a list oI all the entries oI T using the convert operation. This does not change T, it just creates an additional list structure that has the same data as T's entries which can be assigned to another variable. (14.17)
(14.18) (14.19)
II we want to Iill up a table by giving a multiple entries at once, we can give the table Iunction a list oI equations indicating indices and the associated value.
14.4 Troubleshooting with tables 283 There are three major diIIerences between tables in Maple and the data containers we've seen previously: a) there is a separate creation step (creating a table), b) you can change the contents oI the table be creating, changing or deleting an item/entry c) items within a table are stored under a kev or index value. The latter works similar to the indexing used Ior lists, but the index does not have to be an integer. A table can store any kind oI item under any kind oI key. For the time being, we will stick with integer keys, but eventually we will take greater advantage oI this "key" Ieature. 14.4Troubleshooting with tables 1. Table creation tbl . table( ); should always appear at the beginning oI a script, which assigns tbl a Iresh, empty table. II you don't do this, you may see items leIt over in tbl Irom the last time you executed a script in the same worksheet with tbl in it. Alternatively, you can do a restart; beIore running a script that uses a table. 2. Use entries and indices to see what's in your table. Check the results to make sure that there are no unexpected indices and that the values are computed correctly. 3. Be able to recall the circumstances where you should use square braces | | and when to use parentheses ( ) in working with tables. Troubleshooting with tables: mistaking ] and ( ) (14.20)
Error, invalid leIt hand side in assignment
Accessing a table value requires the use oI square brackets | | to enclose the index. Use oI parentheses makes Maple think you are talking about Iunctions rather than tables.
(14.21)
We place an entry into the table -- the value 4.7 accessed by the key 3. (14.22) (14.23)
This does not access values in the table. It uses ( )s rather than the necessary | | s. Troubleshooting tables: checking for extra keys (14.24) This a demonstration oI how the Iact that "a table key can be any value" can create conIusion. We create a table and place three entries into it. 284 14 Tables and other data structures Troubleshooting tables: checking for extra keys (14.25) (14.26) (14.27)
(14.28)
(14.29) (14.30) (14.31) (14.32) (14.33) (14.34)
We assign i, f, and k the values oI 2, 3.0 and 4.
We expect that this will result in creating or changing certain entries oI the table. (14.35)
Where did the 5.0 go? We thought we did T|3.0| : 5.0 with the use oI k (14.36) We use the indices and entries Iunctions to tell us what is going on in T. Evidently the keys used Ior T include both 3 and 3.0. 14.5 Using sequences in multiple simultaneous assignments 285 Troubleshooting tables: checking for extra keys (14.37)
The light bulb in our heads comes on where we recall that 3 and 3.0 are regarded as diIIerent in Maple. "3" is an exact integer and "3.0" is a Iloating point number. (14.38) (14.39) (14.40) (14.41) (14.42)
We see that there are two distinct entries in the table. Reassigning one oI them does not erase the other entry, although the value oI the Iirst one does change. (14.43) (14.44) (14.45)
As indicated in the demonstration oI tables, unassigning a table entry will erase it Irom the table. 14.5Using sequences in multiple simultaneous assignments Maple provides a way oI doing several assignments at once. Rather than variable . expression; we can give sequences on both sides: variable1 , variable2 : expression1, expression2; 286 14 Tables and other data structures will assign variable1 the value oI expression1, and variable2 the value oI expression2. 3 or more assignments can be perIormed in a similar Iashion. Use sequences to do multiple simultaneous assignments. (14.46) a=1, b is 3.141593, c is arctan(1/3*Pi) a=1.000000, b is 3.141593, c is 0.808449
Multiple assignment at work. This is also a demonstration that the I Iormat will Iorce an evalI approximation as long as the value is some kind oI real number. Error, ambiguous multiple assignment Error, ambiguous multiple assignment
We get error messages iI the number oI variables assigned don't match the number oI values being supplied on the right hand side. Maple regards this as "ambiguous" because we could be thinking oI assigning a the value 1, and b the sequence 3.1415..., arctan( ) or perhaps assigning a the sequence 1, 3.1415..., and b the value arctan( ) . Yet another possibility is to assign a the value NULL, and b the sequence 1, 3.1415..., arctan( ) . Maple doesn't try to decide and signals an error instead. (14.47) (14.48) (14.49)
II there's only variable on the leIt hand side, then it is assigned the entire sequence as a result. We can use a sequence in a Iashion similar to a list. 14.6 Using multiple assignment with procedure results: return sequences oI results 287 The one time that you run into problems with this approach is when some oI the values you want to assign are sequences themselves. Maple automatically combines sequences separated together by commas into a single sequence. This is a situation where it is better to use lists as the values, since two lists don't automatically combine with a comma. A tricky situation: sequences of sequences (14.50) (14.51) (14.52)
We see that sequences blend together into a single sequence when combined together with a comma. Error, ambiguous multiple assignment
Maple can't tell what part oI 1,2,x,y is supposed to go to var1, and what part is supposed to go to var2.
(14.53) (14.54) (14.55) (14.56)
A sequence oI lists doesn't automatically combine the lists together. This allows us to do multiple assignment unambiguously. 14.6Using multiple assignment with procedure results: return sequences of results OIten the programmer wants a procedure to calculate several things at once. We can Iinesse the limitation that Maple procedures can return only one result by making that result a sequence. We can then do multiple assignment to separate out the pieces. #This procedure takes two lists of scores from n tests. #It finds the average of the best scores, and the average #of the worst scores maxMinAvg := proc(list1, list2) local i, n, smax, smin; 288 14 Tables and other data structures #Initialize the accumulator variables smax, smin:= 0,0; n:= nops(list1); #Add together the maximum and minimums. for i from 1 to n do smax := smax + max(list1[i], list2[i]); smin := smin + min(list1[i], list2[i]); end do; return smin/n, smax/n; end proc; L1 := [ 95, 75, 74, 83]; L2 := [ 72, 98, 0, 85]; worst, best := maxMinAvg(L1, L2); printf("Avg of best scores is: %4.2f\nAvg of worst scores is: %4.2f", best,worst); L1 := [ 10, 9, 7.5, 6.4, 7.4]; L2 := [ 8, 8, 8, 8, 9]; worst, best := maxMinAvg(L1, L2):#suppress output with a colon printf("Avg of best scores is: %4.2f\nAvg of worst scores is: %4.2f", best,worst); Avg of best scores is: 88.00 Avg of worst scores is: 57.50 Avg of best scores is: 8.80 Avg of worst scores is: 7.46 14.7 A pattern oI looping: accumulation oI results 289 14.7A pattern of looping: accumulation of results Many for and while loops accumulate results: they use variables whose value is updated each loop repetition to be incrementally more than they were beIore. For example, the smax and smin variables oI the previous section are are initialized beIore the loop as zero. Each trip through the loop they accumulate one more term oI the sums. When the loop ends, their values will be the sum oI all the maxes and mins, respectively. Thus the role oI smax and smin are as accumulators; the loop oI the procedure might be reIerred to as an accumulation loop. Tables can be used as accumulators as well. Rather than adding together data, they accumulate all the results oI a particular variety as entries in the table. When the loop is Iinished, the table will be a data container holding all oI the computed results oI that variety. The example in the next section shows a way as well. 14.8Application of tables in accumulative looping Problem: a little old lady deposits some money into a savings account, which pays an interest rate of r paid yearly. She leaves it in the account for numYears years. Calculate how much money she will have at the end of this time. Also, plot the growth of her money over time. Solution: To handle this problem, we couple two ideas: 1. We use a loop to calculate the amount in the account. II A is the amount on deposit, then newA : A r*A; expresses the relationship that the amount in the next year will be the current amount plus the interest. (We're assuming that r is a decimal Iraction representing the interest, e.g. r is .03 iI we are talking about 3 interest. AIter doing the computation , we can do A : newA; to set up the loop Ior the next iteration. It's not diIIicult to write a procedure that does this. We parameterize it by choosing initialAmt to be the amount Iirst deposited, rate the interest rate, numYears the number oI years. We could use i, r, and N as the parameter names instead but choose the longer ones because it helps remind us oI the intended purpose oI each parameter.
interestCalculator := proc (initialAmt, rate, numYears) local i, A, newA; #initialize A A := initialAmt; #Calculate new amount based on present amt #and interest rate for i from 1 to numYears do newA := A + rate*A; A := newA; #Get ready for next loop trip end do; return A;
290 14 Tables and other data structures end proc; (14.58) (14.59)
We get a dollar amount by clicking on the result Irom the computation and doing right-click -~ Numerical Formatting -~ Currency. AIter we get this working, we add in the second idea: 2. We use tables to accumulate the year-values and the amount-values so that we can generate a plot. Once we have accumulated the values, we convert the tables into lists because the plot Iunction wants lists oI values.
interestCalculator2 := proc (initialAmt, rate, numYears) local i, A, newA, yearTab, amtTab;
#Calculate new amount based on present amt #and interest rate for i from 1 to numYears do
newA := A + rate*A; A := newA; #Remember this year's info. We develop a version oI the procedure so that it returns a plot structure. Note the use oI sprintI to create a title that changes when the parameters change. 292 14 Tables and other data structures yearTab[i] := i; amtTab[i] := A; end do; return plot(convert(yearTab,list), convert(amtTab,list), style=POINT, color="Red", symbol=diamond, labels=["years", "dollars"], title=sprintf("Growth of a $%5.2f deposit at %4.2f percent interest",initialAmt, rate*100)); end proc:
Looking at the compound interest Ior this period oI time, we can see that the growth is beginning to diverge Irom being a straight line. Having developed the idea Ior this procedure in pieces, we create a single procedure that returns both results as a sequence. interestCalculator4 := proc (initialAmt, rate, numYears) local i, A, newA, yearTab, amtTab;
#Calculate new amount based on present amt #and interest rate We develop a version oI the procedure so that it returns a plot structure. Note the use oI sprintI to create a title that changes when the parameters change. 14.8 Application oI tables in accumulative looping 293 for i from 1 to numYears do
newA := A + rate*A; A := newA; #Remember this year's info. yearTab[i] := i; amtTab[i] := A; end do; return amtTab[numYears],plot(convert(yearTab,list), convert(amtTab,list), style=POINT, color="Red", labels=["years", "dollars"], title=sprintf("Growth of a $%5.2f deposit at %4.2f percent interest",initialAmt, rate*100)); end proc: (14.62) (14.63)
Our little old lady might be really, really old aIter 40 years, but it is an instructive demonstration oI compound interest that someone younger might use. The graph shows why doing retirement savings in your twenties has much more impact than equivalent savings in later years. Note that the graph does not get drawn when it is assigned as part oI a sequence oI two values. In order to see it, we have to ask Maple to display the value oI the variable that was assigned the plot structure.
294 14 Tables and other data structures interestCalculator5 := proc (initialAmt, rate, numYears) local i, A, newA, yearTab, amtTab;
#Calculate new amount based on present amt #and interest rate for i from 1 to numYears do
amtTab[i] := amtTab[i-1] + rate*amtTab[i-1]; #Remember this year's info. yearTab[i] := i; end do; return amtTab[numYears],plot(convert(yearTab,list), convert(amtTab,list), style=POINT, color="Red", labels=["years", "dollars"], title=sprintf("Growth of a $%5.2f deposit at %4.2f percent interest",initialAmt, rate*100)); end proc: We notice that the use oI A/newA and amtTab are somewhat redundant. Using the ability to reIerence previously stored values in the table, we rewrite the loop to use amtTab|i| Ior newA and amtTab|i-1| Ior the previously calculated value oI A. As the loop runs, it reIers to amtTab|1| and amtTab|0| the Iirst time through the loop, amtTab|2| and amtTab|1| the second time, etc. Everything is placed in the table in the correct place to make this kind oI indexing work. (14.64) (14.65) This version oI the procedure produces the same result as the last, but it is a Iew lines shorter. For those who are comIortable with equations such as , this is the way it's done in the syntax oI a typical programming language. 14.9 Summary oI Chapter 14 295
14.9Summary of Chapter 14 Type of container Examples How to create it How to access a part of it Operations that can be performed with container Ways of changing data container after it's been created Table T : table(); T|1| : 32.5; T|2| : 32.6; tblName : table();
This creates an empty table and assigns it to the variable tblName replacing whatever previous value it had. T|kev| retrieves the value stored under the key Irom within the table. Thus iI you have done T|1| : 32.5; then subsequently doing T|1| will retrieve the 32.5.
The kev can be any value Maple expression. Thus x, or t3..5 can be kevs Ior a Table provides a sequence oI the values stored in the table (including duplicate values)
indices(T) provides a sequence oI the kevs used by the table.
convert(T,list) creates a list oI the entries oI T. The entries will be listed in the order Maple uses Ior the indices. When the Key-value assignment: T|1| : 32.7 296 14 Tables and other data structures Type of container Examples How to create it How to access a part of it Operations that can be performed with container Ways of changing data container after it's been created indices are non-negative integers, this will be the expected order. The order will be less predictable when non-integer indices are used. Use sequences to do multiple simultaneous assignments. (14.66) a=1, b is 3.141593, c is arctan(1/3*Pi) a=1.000000, b is 3.141593, c is 0.808449
297 15More on looping 15.1Chapter Overview We Iirst look at another way oI creating an animation in Maple, using a variant oI the plots|display| operation. This way oI creating animations is useIul in situations where it is inconvenient to describe the animation through a single mathematical Iunction oI a time variable t. Many activities in programming use repeated actions to accomplish a result. We've already seen this in Chapters 11-14 in the application oI while and for. In this chapter, we look at patterns oI looping driven by their application. We also look at a number oI operations Irom the Maple library that cause repetition to happen even without explicit loop programming. Knowing and using these short-cut operations that use looping implicitly can save you time coding and troubleshooting. 15.2Animations, revisited We've seen how the displav operation oI the plots package can be used Ior multiplotting -- creating a single plot that combines together separately created plots. II insequencetrue is given as the second parameter to displav,, then an animation will be created with each element oI the list oI plots given displayed, one per Irame oI the animation. General Iorm: plots|display|( list of plot structures, insequencetrue, other plot options) creates an animation Irom a list oI plots or plot structures. Problem: Create an animation with two parts: a square 1 unit wide and long moves from (0,0) to (0,1). Then it moves sidesways to (1,1) while smoothly growing to be a square 1.5 units wide and long. Solution: write a loop that generates the frames for the first part of the animation. Then add on more code that generates the frames for the second part of the animation. Use display(..., insequencetrue) with the list of plots. restart; #Use drawBoxB function to draw a box drawBoxB := proc(x0, y0, width, height, c, plotTitle) local L1, L2, L3, L4, ptlf; #short hand abbreviation of line ptlf := plottools[line]; #this avoids having to remember to do "with(plottools)" in the session. L1 := ptlf([x0, y0], [x0+width, y0], color=c); L2 := ptlf([x0, y0], [x0, y0 + height], color=c); L3 := ptlf([x0+width, y0], [x0+width, y0+height], color=c); L4 := ptlf([x0, y0+height], [x0+width, y0+height], color=c); plots[display]([L1, L2, L3, L4], title=plotTitle); end proc; movie1 := proc(u1, u2, numsteps1, numsteps2, boxColor) local indexTab, frames, frames2, i, h, uh, s1, s2, s3, L1; #initialize tables frames, frames2:= table(), table();
#part 1 -- draw square u1 units wide moving from (0,0) to (0,1) taking numsteps1 frames. #h is the step distance 298 15 More on looping h := (1-0)/numsteps1; #step size of movement for i from 0 to numsteps1 do frames[i] := drawBoxB(0,0+i*h,u1, u1, boxColor, "Part 1"); end do; #part 2 -- draw square growing from u1 units wide #to u2 units wide in numsteps2 steps, #moving from (0,1) to (1,1) in numsteps2 frames. #h is the distance step size #uh is the size step size h := 1/numsteps2; uh := (u2-u1)/numsteps2; frames2 := table(); for i from 0 to numsteps2 do frames2[i] := drawBoxB(0+h*(i),1,u1+uh*(i), u1+uh*(i), boxColor, "Part 2"); end do;
#Convert tables into lists, then the two lists into sequences #Section 6.8 (p. 85) talked about this conversion. s1 := op(convert(frames,list)); s2 := op(convert(frames2,list)); #Merge the two sequences into a single sequence s3 := s1, s2; #convert the sequence into a list L1 := [s3]; #Create a movie of all the frames plots[display](L1, insequence=true); end proc; #Test 0 Draw a box printf("Test 0 -- draw a box\n"); drawBoxB(0, 0, 1, 1,"Red", "Box Test"); #Test 1 #draw red square 1 unit in size changing into #a square 1.5 units in size. #Part 1 is 11 frames long, Part 2 is 16 frames long. printf("Test 1 -- do a two part movie\n"); movie1(1, 1.5, 10, 15,"Red"); 15.2 Animations, revisited 299 Test 0 -- draw a box Test 1 -- do a two part movie 300 15 More on looping The table below shows several Irames oI the animation. Table 15.1: Several frames of movie1 animation
Frame 1 (Iirst Irame) oI animation Frame 12 Frame 20 Frame 27 (last Irame) It is sometimes easier to code an animation one Irame at a time, separately, rather than try to Iigure out how to represent all the dynamics in a single Iormula involving x,v, and t as the animate operation discussed in Chapter 9 required. Programmers used to Iunctional notation will daisy chain together some operations and will avoid as many variables. This might be what a more experienced programmer would do iI they thought that their intended readership could keep up. A programmer might use variables Ior intermediate results s1, s2, s3, L1, L2, iI the same result was to be used several times, or iI they wanted to print out the value oI the intermediate result Ior debugging purposes along the way. But here they are used only as a temporary way points to the Iinal result, so we can do without them. The code region below illustrates the same program without use oI those intermediate variables. It does the same thing, but it is shorter. restart; #Use drawBoxB function to draw a box drawBoxB := proc(x0, y0, width, height, c, plotTitle) local ptlf; #short hand abbreviation of line ptlf := plottools[line]; #this avoids having to remember to do "with(plottools)" in the session. plots[display]([ ptlf([x0, y0], [x0+width, y0], color=c), ptlf([x0, y0], [x0, y0 + height], color=c), ptlf([x0+width, y0], [x0+width, y0+height], color=c), ptlf([x0, y0+height], [x0+width, y0+height], color=c)], title=plotTitle); end proc; movie1 := proc(u1, u2, numsteps1, numsteps2, boxColor) local indexTab, frames, frames2, i, h, uh; #initialize tables frames, frames2:= table(), table();
#part 1 -- draw square u1 units wide moving from (0,0) to (0,1) taking numsteps1 frames. #h is the step distance 15.3 Combining Ior and while 301 h := (1-0)/numsteps1; #step size of movement for i from 0 to numsteps1 do frames[i] := drawBoxB(0,0+i*h,u1, u1, boxColor, "Part 1"); end do; #part 2 -- draw square growing from u1 units wide #to u2 units wide in numsteps2 steps, #moving from (0,1) to (1,1) in numsteps2 frames. #h is the distance step size #uh is the size step size h := 1/numsteps2; uh := (u2-u1)/numsteps2; frames2 := table(); for i from 0 to numsteps2 do frames2[i] := drawBoxB(0+h*(i),1,u1+uh*(i), u1+uh*(i), boxColor, "Part 2"); end do;
#Convert tables into lists, then the two lists into sequences plots[display]([op(convert(frames,list)), op(convert(frames2,list))], insequence=true); end proc: #Suppress listing the procedure #Test 0 Draw a box printf("Test 0 -- draw a red box\n"); drawBoxB(0,0,1,1,"Red", "Box Test"); #Test 1 #draw red square 1 unit in size changing into #a square 1.5 units in size. #Part 1 is 11 frames long, Part 2 is 16 frames long. printf("Test 1 -- do a two part movie\n"); movie1(1, 1.5, 10, 15, "Green"); 15.3Combining for and while Maple's syntax allows the use oI an stepper variable and a continuation condition (other than that oI the stepper variable reaching a Iinal value. for stepperJariable from initialJalue to finalJalue by stepJalue while condition do .... end do promotes a repetition which stops when either the stepperVariable reaches the finalJalue, or the condition becomes Ialse. II the to initialJalue is omitted, then the while condition is the sole criterion used to decide whether to continue the repetition. This can abbreviate the coding in many standard cases. Example of for and while repetition: accumulate terms of a sum until next term is very small. The code region below computes the sum
302 15 More on looping until it Iinds a term that is tiny (less than the value oI the parameter tol). Compared to the previous example, the main diIIerence is that we can skip the initialization and increment oI the stepper variable i since the for loop handles it Ior us automatically. Since there is no finalJalue, the loop will not stop because the stepper variable reached a Iinal value. However, at the start oI each repetition, the condition abs(term)~tol will also be checked. This is what stops the repetition aIter a Iew trips through the loop. restart; sumIt := proc(x,tol) local term, s, i; #Variables that will be used within the procedure. # Initialize script parameters #tol is the size of the stopping criterion. #x is the value of sin(x) that we are trying to approximate #Initialize accumulation variables to first term of sum. term := x; s := x; #s accumulates the sum, we initialize it to the first term. #add on successive terms for i from 3 by 2 while abs(term)>=tol do term := (-1)^((i-1)/2)*(x^i)/i!; printf("term is %e\n", term); s := s+term; end do; end proc; #Test 1 x := .3; tol := 10^(-2); #want at least two decimal digits to be stable. #Print out the final sum, and compare it to what it's supposed to be. printf("Test 1, sum is: %e compared to %e.",sumIt(x,tol), sin(x)); #Test 2 -- same argument for x, smaller tolerance. x := .3; tol := 10^(-5); #want at least five decimal digits to be stable. #Print out the final sum, and compare it to what it's supposed to be. printf("Test 2, sum is: %e compared to %e.",sumIt(x,tol), sin(x)); 15.4 Patterns oI looping 303 term is -4.500000e-03 Test 1, sum is: 2.955000e-01 compared to 2.955202e-01. term is -4.500000e-03 term is 2.025000e-05 term is -4.339286e-08 Test 2, sum is: 2.955202e-01 compared to 2.955202e-01. We can get more decimal places oI agreement between our approximation and the reIerence result by changing the value oI tol. This will cause more repetitions oI the loop. We would get an inIinite loop (a bug) iI term doesn't become tiny eventually in the repetition, but we know that it will, since .
One surprising Iact about this approximation is that it works very well Ior small values oI x. Only a Iew multiplications and sums gives us an approximation to sin(x)) that's accurate to seven decimal digits.
While the built-in sin procedure is a perIectly good substitute Ior writing a loop, there are situations where this approach will work at approximating a Iunction that there is no built-in library procedure Ior. You'd want to ask a numerical analvst to provide assurances that it's going to work well. 15.4Patterns of looping We have introduced quite a lot oI machinery. It can be easy Ior beginners to be uncertain about the connection between intent (what you want to achieve) and svntax (how you say it in the programming language). Here as a short table summarizing the connections we have introduced so Iar Patterns of looping 304 15 More on looping Intent Example Repeat exactly the same thing n times to 5 do print("I will not teach others to fly"); end do; (15.3) The action within the loop depends on the value oI variable stepping Irom an initial to a Iinal value, adding a Iixed amount to the stepper variable between each step for t from 0 by .1 to 1 do printf("arccos(%f) = %f\n", t, arccos(t)) end do; arccos(0.000000) = 1.570796 arccos(0.100000) = 1.470629 arccos(0.200000) = 1.369438 arccos(0.300000) = 1.266104 arccos(0.400000) = 1.159279 arccos(0.500000) = 1.047198 arccos(0.600000) = 0.927295 arccos(0.700000) = 0.795399 arccos(0.800000) = 0.643501 arccos(0.900000) = 0.451027 arccos(1.000000) = 0.000000 Accumulation: Variables within the loop accumulate results. Each repetition incrementally changes onto the partial result. When the repetition is Iinished, the entire result has been computed. x := .3: #Parameter prod := 1: #Accumulation variable #"sum" and "product" are reserved Maple names #So we should use something else like "s" or "prod" #for variables. #Compute the product of (x+2)*(x+3)*(x+4)*...(x+15) for i by 2 to 15 do prod := (x+i)*prod; end do: #Suppress execution trace inside the loop
print(prod); (15.4) The loop is repeated while a continuation condition is true. (The loop stops when the continuation condition is no longer true.) This computes an approximation to
15.5 Constructing iterations and the roles oI variables 305 .
#script parameters x := .2: tol := 10^(-6): #accumulation variables, initialized i := 1: s := 1: #First term of sum term := 1: #Next term of sum while (abs(term)>=tol) do term := (x^(i))/(i!); s := s + term; i := i+1; end do: printf("compare %e to %e\n", s, exp(x)); compare 1.221403e+00 to 1.221403e+00 15.5Constructing iterations and the roles of variables Setting up iterations is one oI the most prized skills Ior a programmer, and one oI the most diIIicult Ior beginners to learn. To construct an iteration Irom scratch, we recommend the Iollowing process: Without trying to create an iteration, just write down the series oI directions Ior the computational process you want to program. II you keep on writing down steps, eventually you will notice similarities between actions in the series. OIten times the similarity allows you to discover that rather than giving a new variable name to every result you compute, you can reuse certain variables because you no longer need them beyond a certain point in the series. Finding the pattern is key. Once you have it, then the repeating pattern becomes the loop body. Steps beIore the repetition kicks in become initiali:ation beIore the loop. Usually there are summary actions (e.g. making a plot or animation, oI all the results computed by the loop) which become part oI the post-loop actions. Only through experience do you get to the point where you can construct loops without explicitly Iinding the repetition pattern is. Don't expect it to come without practice and thoughtIul reIlection on experience. In trying to construct a code Ior a successIul loop, it can be good practice to decide upon the role oI each variable you are using. II you are unclear about a variable's role or purpose, it may mean that the variable is superIluous. It could also mean that you have skipped over a key computational action which you need to develop code Ior. Here are typical roles variables can play in a loop: Roles Jariables that are fixed values. They are assigned during the initialization but don't change aIterwards. Jariables that are steppers. Stepper variables change value methodically with each iteration oI the loop. Jariables that gather the final result. Each repetition oI the loop leaves the accumulation variable one step closer to its Iinal objective (e.g. adding together all the terms oI a sum). Jariables that hold the most recent value going through a succession. Usually (but not always) the most recent value is computed Irom previous values. 306 15 More on looping Jariables that hold the previous value. Sometimes in order to compute the next value, it is necessary to keep not only the present value, but the one before that. Since a variable can hold only one value at a time, an extra variable needs to be used to play that role. The examples given so Iar do not have any variables with this role, but we will soon see situations where this is needed. Consider Ior example this starter code Irom Lab 2, that computed chemical concentrations Lab 3 CS 122 Chemical problem starter code #Lab 2 Problem 2.1 restart; #just in case there are unwanted assignments hanging around from #previous runs. # Chemical reaction modelled by Lotka-Volterra Model #Discrete approximation numTimeSteps := 50; #Initial concentrations A0 := 1000; B0 := 0; X0 := 10; Y0 := 50; #Chemical constants k1 := .001; k2 := .001; k3 := .1; Atab := table(); indexTab := table(); A := A0; B := B0; X := X0; Y := Y0; for i from 1 to numTimeSteps do #Calculate next values of chemical concentrations newA := A - k1*A*X; # newX := # newY := # newB := #Update all four chemicals A := newA; #B, X, Y updated similarly. indexTab[i] := i; Atab[i] := A; #Each entry is a (time, concentration) end do: with(plots): with(plottools): #Given a table of x coordinates and a table of y coordinates, #Create a point plot. Fplot := (itab,vtab,COLOR) -> plot(convert(itab,list),convert(vtab,list), color=COLOR, symbol=diamond, style=point); #Display this point plot, along with a title and labels. display([Fplot(indexTab,Atab,"Green")], title="graph of A", labels=["time", "concentration"]); 15.5 Constructing iterations and the roles oI variables 307 The analysis oI the roles oI variables in this code is as Iollows: Roles Example in CS 122 Lab 3 Problem 2.1 Jariables that are fixed values. They are procedure parameters or are assigned during the initialization but don't change aIterwards. k1, k2, k3 are Iixed values. So are A0, B0, X0, and Y0. So is numTimeSteps. Jariables that are steppers. Stepper variables change value methodically with each iteration oI the loop. i is a stepper variable. It begins at 1. One is added onto its value each trip through the loop, so it steps through the values 1, 2, 3, .... Jariables that gather the final result. Each repetition oI the loop leaves the accumulation variable one step closer to its Iinal objective (e.g. adding together all the terms oI a sum). While there are no variables that sum or count in this example, indexTab and Atab are tables that store one value per iteration. The tables gather the whole collection oI values generated during the simulation, which are needed to produce the plot which is the Iinal result. Jariables that hold the most recent value going through a succession. Usually (but not always) the most recent value is computed Irom previous values. newA is holds the most recent value oI the concentration oI chemical A. newB, newX, and newY also take on this kind oI role. Jariables that hold the previous value. Sometimes in order to compute the next value, it is necessary to keep not only the present value, but the one before that. Since a variable can hold only one value at a time, an extra variable needs to be used to play that role. The examples given so Iar do not have any variables with this role, but we will soon see situations where this is needed. At the beginning oI the loop, A (and as the code was developed, B, X, and Y) took on the role oI the previous value. It was used to compute newA, newB, etc. At the end oI the loop body, A is set to the most recent value in preparation Ior the next iteration oI the loop when those values will once again become "previous". Here's a classic example oI a task accomplished through a loop: Iinding the smallest value oI a list oI numbers An example using a variable that holds the previous value #We want to find the smallest value in a list of numbers L := [3, 6, -4, 2, 1, 9]; #minSoFar's role is an accumulator variable: # it keeps track of the "smallest number so far". We initialize it to infinity # so that whatever we see first will automatically become the smallest so far. minSoFar := infinity; #Step through all the positions of L: 1, 2, 3... 6 for i from 1 to nops(L) do printf("Comparing %a to %d\n", minSoFar, L[i]);
#If the previously seen minimum is larger than L[i].... if minSoFar>L[i] #Make it the new previously computed minimum then minSoFar := L[i]; end if; end do; 308 15 More on looping printf("The minimum is: %a.", minSoFar); Comparing infinity to 3 Comparing 3 to 6 Comparing 3 to -4 Comparing -4 to 2 Comparing -4 to 1 Comparing -4 to 9 The minimum is: -4. The analysis oI the roles oI variables in this code is as Iollows: Roles Example in CS 122 Lab 2 Problem 2.1 Jariables that are fixed values. They are assigned during the initialization but don't change aIterwards. L is the only Iixed variable. Jariables that are steppers. Stepper variables change value methodically with each iteration oI the loop. i is a stepper variable. It begins at 1. One is added onto its value each trip through the loop, so it steps through the values 1, 2, 3, .... Jariables that gather the final result. Each repetition oI the loop leaves the accumulation variable one step closer to its Iinal objective (e.g. adding together all the terms oI a sum). There aren't any "gatherers" in this short bit oI code. Jariables that hold the most recent value going through a succession. Usually (but not always) the most recent value is computed Irom previous values. minSoFar hold the most recent value oI the minimum value seen in L so Iar. BeIore the loop starts, it is initialized at infinity, which guarantees that aIter the Iirst element oI L is inspected it will become the value oI minSoFar. Note that infinity will be printed as the minimum at the end oI the code iI L : | | (the list with nothing in it). Jariables that hold the previous value. Sometimes in order to compute the next value, it is necessary to keep not only the present value, but the one before that. Since a variable can hold only one value at a time, an extra variable needs to be used to play that role. The examples given so Iar do not have any variables with this role, but we will soon see situations where this is needed. minSoFar also plays this role too. As the i-th execution oI the loop body begins, the value oI minSoFar is the minimum oI L|1| through L|i-1| -- the minimum computed Irom all the previous repetitions oI the loop. As the i-th execution oI the loop body ends, minSoFar has changed to be the minimum oI L|1| through L|i|. The code works because iI you know the minimum oI a collection oI numbers, and add a new number to the collection, the overall minimum is the smaller oI the new number and the minimum oI all the other numbers. 15.6lmplicit looping: seq, list addition In chapter 12, we learned about for and its ability to loop with an index (stepping) variable. While this is an abbreviation over the pattern as implemented with while that we saw in chapter 11, it still takes work to set up. Certain repetitious actions occur so commonly that many programming languages provided even shorter ways oI perIorming looping idioms. For example, suppose we wanted to build a list consisting oI the numbers 1,4,9, 25, ... 169. We could type such a list in, but Irom what we know oI looping we suspect that there's an easier way. Using the ideas we've seen so Iar, we could use a table valueTab that has an accumulation 15.6 Implicit looping: seq, list addition 309 variable L. With i as the stepping variable going Irom 1 to 100, we would Iill up the table with values. AIter the loop Iinishes, we could convert the table into a list to get our result: Making a list through a loop
#initialize table valueTab := table(); #fill up the table for i from 1 to 13 do valueTab[i] := i^2; end do; #Produce list as result L := convert(valueTab,list): printf("L is: %a", L); L is: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169] The nice thing about this loop is that it is no more work Ior us to create a list with 100 items 1, 4, 9, ... 10,000. All we have to do is change the "13". However, there is an even shorter way to create this list. Maple has a Iunction seq whose syntax borrows heavily Irom for. The seq Iunction creates a sequence as indicated by the values oI the stepping variable. To get a list, we convert the sequence into a list, as explained in Chapter 12. Making a list with seq 310 15 More on looping
#initialize table #Create a sequence s := seq(i^2,i=1..13); #Convert it to a list L := [s]; printf("L is: %a", L); L is: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169]
With this kind oI Iacility, it is easy to quickly solve many problems that are solved with Maple Iunctions that take lists. Creating a list of values with seq Create a list oI the approximations to , , ... . We chain together the sequence creation and the conversion to a list in one line oI code.
(15.8)
The general Iorms oI seq are seq( expression involving steppingJariable, steppingJariablerange) and seq( expression involving steppingJariable, steppingJariablerange, stepJalue). The second Iorm behaves like the for... from... to ... by ...do...end do described in the previous chapter. Giving lists to Maple functions using seq with a step value Create a list oI the approximations to , , ... .
(15.9) Adding together the elements oI two lists is another common operation that has a built-in shortcut. Adding together two lists with + 15.6 Implicit looping: seq, list addition 311 Create a list oI values oI (approximately). (15.10) Create a similar list oI values Ior (15.11) Add them together using "". (15.12)
We don't get component-wise "automatic multiplication" with "*". Maple doesn't give an error, but it doesn't do the multiplication, either. (15.13)
We get this done without writing a loop to do it with the use oI seq.
(15.14) "Automatic addition" works with numbers, expressions, lists, sequences, ranges, and equations, but does not work with tables, plots, or sets. "Automatic multiplication" only works with numbers and expressions. Maple does have additional data containers with use with linear algebra, vectors, and matrices Ior which both addition and multiplication work -- but that should wait until you need to do linear algebra. 312 15 More on looping 15.7An example that uses for...while... looping and display(..., insequence=true) for animation Problem: a little old lady deposits some money into a savings account, which pays an interest rate of r paid yearly. She leaves it in the account for numYears years. However, she has a targetAmount in savings in mind, so she will stop as sooner if the target amount is reached. Show the growth of her money over time for a variety of interest rates. interestCalculator6 := proc (initialAmt, loRate, hiRate, numYears, targetAmt) local i, A, newA, yearTab, amtTab, rate, frame, frameIndex;
#Initialize frame (a table of plots) and frameIndex (a counter) frame := table(); #A table of graphs frameIndex := 0;
#Try for a variety of rates
for rate from loRate by .001 to hiRate do #initialize A, and tables. A, yearTab, amtTab := initialAmt, table(), table(); #initialize first entry of table before looping yearTab[0] := 0; amtTab[0] := initialAmt;
#Calculate new amount based on present amt #and interest rate. for i from 1 to numYears while amtTab[i-1] <=targetAmt do amtTab[i] := amtTab[i-1] + rate*amtTab[i-1]; #Remember this year's info. yearTab[i] := i; end do; #loop with years
#Store a plot into the frame table. frame[frameIndex] := plot(convert(yearTab,list), convert(amtTab,list), style=POINT, color="Red", labels=["years", "dollars"], title=sprintf("Growth of a $%5.2f deposit at %4.2f percent interest",initialAmt, rate*100)); frameIndex := frameIndex +1; #update frameIndex (counter) end do; #loop with rates
#Create an animation with all the graphs together plots[display](convert(frame,list),insequence=true); end proc: The program is written as a nested loop. For each value oI the interest rate, we go through the calculation described in interestCalculator5 oI the previous chapter. The inner loop rather than being a straight repetition with i taking on all the values Irom 1 to numYears, will stop early iI the target amount is ever reached early.
Recall Irom Chapter XX that the op operation is a way oI selecting parts oI an expression. II rateRange is the range (.5)..(.6). op(1,rateRange) is .5 and op(2,rateRange) is .6. 15.7 An example that uses Ior...while... looping and display(..., insequencetrue) Ior animation 313
This produces an animation Ior various rates oI interest. We show the Iirst Irame oI the animation here. As described in Chapter 6, the animation player can be used to play the animation.
We show a Iew Irames Irom the animation here. For the last Iew Irames, the amount on deposit eventually exceeds targetAmt, so no data points are displayed above that level. This is because the Ior...while loop in the simulation stopped repeating without reaching numYears because the while condition became true beIore the limit oI the for repetition was reached.
The animation shows a series oI plots. The idea is "the 314 15 More on looping Frame 1 Frame 8 Frame 29
interest rate is higher as time elapses in the animation". It is not literally showing a process that changes over time since a Irame oI the animation shows how the deposit amount increases over time.
15.8Summary of Chapter 15 Animations through plots[displav](..., insequencetrue)
To create an animation Irom a list oI plot structures, do
with(plots): display(list of plots, insequencetrue);
or
plots|display|(list of plots, insequencetrue);
Either will create an animation where each plot in the list is a single Irame oI the animation.
Plot options given as additional arguments will aIIect all the Irames. For example,
plots|display|(list of plots, insequencetrue, axesnone); 15.8 Summary oI Chapter 15 315
will remove the horizontal and vertical axes Irom all Irames oI the animation.
Creating a sequence through seq seq( expr, varlo..hi) will create a sequence using the index variable var looping through the values lo, lo1, lo 2, ... hi.
Example:
(15.15)
Adding all the elements oI two lists together, element-wise (15.16) (15.17) (15.18) Note: list subtraction works in the same way, but list multiplication does not. A single loop with both for and while control Maple's syntax allows the use oI an stepper variable and a continuation condition (other than that oI the stepper variable reaching a Iinal value.
for stepperJariable from initialJalue to finalJalue by stepJalue while condition do .... end do promotes a repetition which stops when either the stepperVariable reaches the finalJalue, or the condition becomes Ialse. II the to initialJalue is omitted, then the while condition is the sole criterion used to decide whether to continue the repetition. This can abbreviate the coding in many standard cases.
Example 316 15 More on looping
restart; sumIt := proc(x,tol) local term, s, i; #Variables that will be used within the procedure. # Initialize script parameters #tol is the size of the stopping criterion. #x is the value of sin(x) that we are trying to approximate #Initialize accumulation variables to first term of sum. term := x; s := x; #s accumulates the sum, we initialize it to the first term. #add on successive terms for i from 3 by 2 while abs(term)>=tol do term := (-1)^((i-1)/2)*(x^i)/i!; printf("term is %e\n", term); s := s+term; end do; end proc; #Test 1 x := .3; tol := 10^(-2); #want at least two decimal digits to be stable. #Print out the final sum, and compare it to what it's supposed to be. printf("Test 1, sum is: %e compared to %e.",sumIt(x,tol), sin(x)); term is -4.500000e-03 Test 1, sum is: 2.955000e-01 compared to 2.955202e-01.
15.8 Summary oI Chapter 15 317 Variable types Fixed value These variables are set beIore the loop begins, and do not change while the loop is being executed. Steppers These variables change some Iixed amount every time a loop iterates. They hold the current step a loop is on. For example, the index variable in a Ior loop is a stepper variable. Variables that gather the Iinal result These variables accumulate a result that is returned at the end oI a loop. Variables that hold the most recent value in a loop These variables hold some value that was computed during the current iteration oI a loop. They are oIten compared to a previous value to compute a change. Variables that hold a previous value in a loop These variables hold some value computed in the previous iteration oI a loop. 318 15 More on looping 319 16Calculus and optimization 16.1Chapter Overview One oI the most distinctive Ieatures oI Maple is its ability to do mixed computations where the results are a mixture oI Iormulas and numbers. We introduce some oI the built-in Iunctions Ior doing calculus: diIIerentiation, limits, and Iinding minima and maxima. Like solve, the minima and maxima-Iinders come in two styles -- one that tries to calculate Iormulae Ior answers (exact calculation) and one that uses approximation techniques that work only when the answer is numeric. 16.2Learning about additional kinds of mathematical computations We have become accustomed to looking at problems that can be attacked by using some combination oI solve, plot (and other visualization tools), and numerical evaluation/assignment. Contrasting this with the kind oI calculation available Irom today's calculators, we observe that it is diIIerent qualitatively Irom the calculation provided by a calculator because a) Programming (e.g. looping) allows us to do much larger quantities oI calculation than we could through operations only through keystroke. b) Programming (procedures and scripts) allows us to more easily reuse calculations on similar but diIIerent problems. c) The document interIace allows us to record the results and commentary, Ior Iuture reIerence and/or use in presentations and reports. d) PowerIul operations such as solve make solving certain types oI problems much more convenient, even with the work to needed to enter the expression into the computer. e) PowerIul visualization and animation Ieatures available on a computer enhance understanding oI the phenomena being studied. In addition to programmability and a more extensive user interIace, computers in 2012 have another edge over calculators -- they can conveniently access much more library programming because they have access to more Iiles and more interIace Ilexibility. Systems such as Maple, Mathematica and Matlab use this room to provide thousands of extra mathematical features. Some oI it is immediately useIul to Iirst year university/college students in the Iorm oI svmbolic computation -- results Irom calculus. Some oI it involves operations and Iunctions that you will hear about aIter the Iirst year -- linear algebra, multivariate calculus, ordinary and partial diIIerential equations, Laplace transIorms, etc. Learning how to operate a system such as Maple on the basic Ieatures gives you the understanding to pick up many oI the more advanced Ieatures on your own, aIter you learn the mathematics. Right now, we exploring some oI operations that are comprehensible with Iirst year mathematics. However, no course could possible teach all the Ieatures needed in a career. Taking advantage oI systems with thousands oI Ieatures means users must be able to learn on their own aIter their initial period oI training. The process is still the same -- using a combination oI written documentation and interaction with more experienced users. However, no matter how good the support system is, there will always be gaps that the user will have to Iill in, through thought and experimentation, on their own. It's work to do this, but the payoII is that you are Ireed Irom only using the Ieatures you saw in a course. 16.3Differentiation, simplification As it is taught in traditional Iirst-year calculus, diIIerentiation is an operation on Iunctions. Maple knows how to diIIerentiate all oI the common Iunctions Iound in calculus. It is particularly useIul Ior perIorming diIIerentiation when it would take a lot oI algebraic manipulation to do the operations by hand. diff as a Iunction takes two or more arguments. The Iirst argument must be (or evaluate to) an expression such as or . The second argument must be (or be an expression that evaluates to) the variable oI diIIerentiation. The there are third, Iourth, etc. arguments provided, they are used as variables oI higher derivatives. The result oI diff is an expression or a number iI the derivative is a numerical constant. Evaluation oI a derivative expression can occur through eval as with other expressions. 320 16 Calculus and optimization Table 16.1: Symbolic differentiation using the expression palette
Enter the expression, and then right-click (control-click on Macintosh) to bring up the calculation options. Select diIIerentiate-~x
We can calculate the second derivative with respect to t oI this expression by perIorming diIIerentiation twice. We simpliIy the expression a bit by perIorming the operation simpliIy- ~symbolic.
II we want the document to display the mathematical notation Ior the derivative, we can select Irom the expression palette and then Iill in the slots f and x. We can then get Maple to calculate the derivative by typing control-. Table 16.2: Symbolic differentiation and evaluation of derivatives, textually Example Commentary (16.1) (16.2)
Find the Iirst derivative oI the expression with respect to x.
(16.3) (16.4)
Find the Iirst derivative oI the expression with respect to t.
(16.5)
Find the second derivative oI the expression with respect to t. (16.6) diII's second argument must be the variable oI diIIerentiation. Note that iI the variable doesn't occur in the expression, the derivative (according to the mathematical deIinition) is zero. II 16.3 DiIIerentiation, simpliIication 321 you are surprised by getting a zero derivative, check that you are using the correct variable. (16.7)
simpliIy can reduce the size oI the expression, although Iactor or expand sometimes work better. Sometimes additional trigonometric identities need to be applied, through simpliIy(...., trig). (16.8)
This is a way to compute . Through daisy-chaining, we Iirst calculate the derivative, then do the evaluation. (16.9)
This is a way to compute The result oI evaluation here is a Iormula, not a number, since there were two symbols, t and in the second derivative, but we only evaluated one oI them, t. Table 16.3: Plotting a function and its derivative together Example Commentary (16.10)
We're already used to Iunctions that take one or two arguments.
(16.11) In this example, we plot a "strange" Iunction built out oI trigonometric parts, and plot it and its derivative. Since g is a Iunction g(t) will evaluate to the expression . Thus the plotting variable should be t rather than or some other variable. Recall Irom Chapter 3 that we can get the character u either by using the Greek Palette. Another way oI getting u is to type alpha; Maple will auto-transIorm it typographically.
322 16 Calculus and optimization (16.12)
The value oI Ideriv is an expression involving alpha. In programming, unlike mathematics, variable names oIten have names that are more than one letter long. This is to increase intelligibility to readers looking at the programming. Although it seems minor, ease oI comprehension can play an signiIicant role in the cost oI developing and using soItware, so is an important engineering concern. We plot two expressions together involving the variable on the same plot. The use oI a set }as a Iirst argument to plot to do multiple plots was Iirst explained in section XX.
We need to use as the plotting variable here since the value oI fderiv is an expression involving .
16.3 DiIIerentiation, simpliIication 323 Table 16.4: Plotting a function and its derivative together Example Commentary (16.13)
We can use proc to deIine a Iunction that is mathematically identical to f oI the previous example. x, and v are used as the names oI the Iormal parameters here instead oI a and b, but it still deIines the same Iunction. For "small mathematical Iunctions" such as this one, we generally preIer the use oI since it's shorter. The arrow notation can handle this because the Iunction doesn't involve any use oI for, while, or if. (16.14)
g is the same Iunction as beIore, since I and I2 deIine equivalent Iunctions. We use s in the same way that was used in the previous deIinition, and we've already mentioned that I2 is the same as I. So g2 is identical to g. 324 16 Calculus and optimization
We using t as the plotting variable since g2(t) and diII(g2(t),t) are both expressions involving t.
16.4Limits You can use the clickable interIace to compute limits by selecting the appropriate item Irom the Expression palette and then Iilling in the template as needed. Maple uses calculus techniques (e.g. l'Hpital's Rule) to compute limits symbolically. Table 16.5: Clickable interface version of limits Example Commentary (16.15) The result oI limit can be an expression (possibly involving positive or negative inIinity) as well as the symbol undefined.
(16.16) (16.17) Even though the limit exists as t approaches Irom the right or leIt, they do not agree, so there is no "two-sided" limit. 16.5 Finding minima and maxima by using Maple as a calculus calculator 325 (16.18)
To take a one-sided limit, add a "" or "-" superscript to the limit point. (16.19) Note that the value returned as the limit Ior xa, while true Ior most values oI a, is not really valid Ior a0. The textual version oI taking limits involves the limit Iunction. limit takes at least two arguments. The Iirst argument is the expression that you wish to take the limit oI. The second argument is an equation indicating the limit variable and the limiting value. II you supply a third argument, it indicates whether a "right sided", "leIt sided" limit is desired instead oI a two-sided limit. Table 16.6: Textual version of limits Example Commentary
(16.20)
The Iirst argument is the expression that you wish to take the limit oI. The second argument is an equation indicating the limit variable and the limiting value. (16.21) You can use "inIinity" or "-inIinity" as the way oI speciIying or - textually without use oI the palette. (16.22) The third optional third argument to limit can speciIy a one sided limit. This is the textual way oI speciIying . There is no simple way oI speciIying this (16.23) This is the textual way oI speciIying . It would be nice iI the second argument Ior the textual Iorm oI limit was var -~ limitJalue instead oI var limitJalue, since arrows are the more conventional notation. But because oI the limitations oI Maple's processing capabilities Ior its programming language, it would be more expensive to support arrows Ior both this meaning in limits and the use oI -~ in Iunction deIinitions. So users must get used to using equations rather than the standard math symbol Ior "approaches". 16.5Finding minima and maxima by using Maple as a calculus calculator The minimum or maximum oI a continuous Iunction in an interval is sometimes reIerred to as the local extrema of the function. The Iunction whose extremum you are Iinding is reIerred to as the obfective function. In elementary calculus, you learn how to Iind extrema through the use oI derivatives and a little algebra. 326 16 Calculus and optimization Maple can be used to do such calculations using diff to Iind the derivative, and then Iinding where the derivative is zero through solve or fsolve. The advantages oI doing it with a system such as Maple are the same as with other calculations: a) it is easier to do iI the Iormula is involved or iI you don't remember all the math, b) you can easily organize the inIormation about the problem and its solution using Maple word processing so that the work can be easier to present or read, c) the computer's speed oI re-execution makes it easy to handle a bundle oI similar problems. Table 16.7: Finding the minimum and maximum using textually-specified commands From Anton, Calculus 8th ed. p. 307 problem 13 (modiIied)
Find the absolute maximum and minimum values oI
Ior x in
Solution
We deIine a continuous Iunction (16.24) and compute its derivative symbolically. We generate a plot to get an idea oI where to look Ior minima and maxima. Evidently the minimum is in the interior oI the interval middle and the maximum is at the leIt. 16.5 Finding minima and maxima by using Maple as a calculus calculator 327 (16.25) Finding where the derivative is zero should produce the minimum. (16.26) The minimum is conIirmed to be zero -- the plot seems to indicate that but the picture doesn't let us know whether it's really zero or just really close to zero. (16.27)
Standard calculus procedure is to check out the value oI the end points, since the minimum might be there instead oI in the interior oI the interval. However, the values oI f at both oI the end points are larger than the value at .We conclude that f attains a minimum at x . Table 16.8: Writing a procedure to calculate minimum of a function and produce a plot that will help understanding of it Writing a procedure to calculate minimum oI a Iunction and produce a plot that will help understanding oI it Anton, Calculus, 8th ed. Problem 307 (modiIied)
Find the absolute minimum oI Ior x in |-2..3|
We enter the expression, and plot it on -2..3 using the 2-D plot builder.
328 16 Calculus and optimization
To develop the script, Iirst we do it interactively. We do a chain oI calculations to Iind what is obviously the minimum point.
We had to copy the expression again, and evaluate it at to calculate the minimum value. Once we have a number, we calculate what it is, approximately.
We omit calculating the value oI the objective expression at the end points because the plot tells us that minimum is not located there.
(16.28) (16.29) The next step is to develop the textual version oI this.
We turn the sequence oI actions into a textual script. The parameters are the expression to be minimized, the variable in the expression and the region. The plot is just to help us have a visual check that the numeric answer result is probably correct. Since it's something we decide we'd want to do with 16.5 Finding minima and maxima by using Maple as a calculus calculator 329 (16.30) (16.31) (16.32) (16.33) (16.34)
any version oI a minimization problem, we decide to include it in the script.
findMin := proc(expr,var, interval) local deriv, soln, valAtPoint; print(plot(expr,var=interval)); We turn this into a procedure that does the same thing, returning the minimum value and its location in a list. Unless we print the plot, it won't appear during execution oI the procedure because by deIault Maple only displays the result oI 330 16 Calculus and optimization deriv := diff(expr,var); soln := solve(deriv,var); valAtPoint := eval(expr, var=soln); return [evalf(valAtPoint), var=soln]; end; (16.35) the procedure. print causes something to be printed in addition to the Iinal result.
(16.36)
We solve the minimization problem. 16.6 One-step extrema-Iinding using maximize and minimize 331 (16.37)
Now that we have a procedure, we can solve a similar problem: minimize Ior v in the interval -1..4. We see that the plot supports the numerical calculation that the value oI the expression at the minimum is approximately 1.65 at v . 16.6One-step extrema-finding using maximize and minimize Maple's library provides both exact and approximate numerical Iunctions that do the entire sequence oI steps needed to Iind extrema. In this section, we discuss the Maple Iunctions that provide exact solutions to such problems. The exact version automates the work that the user would have to do with diff and solve. The approximate version will provide usable inIormation in situations where exact solution methods don't work. The Maple Iunction Ior Iinding maxima is, appropriately enough, called maximi:e. II expr is an expression involving a variable x, then maximi:e(expr,xrange) will produce maximum value oI the expression Ior x in that range. II there is no maximum value, or iI Maple can't Iind it, NULL is returned. Thus iI maximi:e returns an answer, it should be "believable", but a result oI NULL doesn't meant that there is no minimum. It may just mean that Maple was unable to Iind it.. infinitv or -infinitv may be an answer iI the Iunction is unbounded within the range. We have already seen max and min, which are also built-in Maple Iunctions. However, they only work on lists, sets oI values. They don't work at Iinding minima or maxima oI expressions. It is oIten a good idea when working on extrema problems to do a plot oI the expression in question, so that you can some notion oI where the maxima will be and what their values will be like. Table 16.9: minimize and maximize minimize and maximize From Anton, Calculus 8th ed. p. 307 problem 13 (modiIied)
Find the absolute maximum and minimum values oI
332 16 Calculus and optimization minimize and maximize
Ior x in
Solution
(16.38) We deIine a Iunction. We generate a plot to get an idea oI where to look Ior minima and maxima. Evidently the minimum is in the middle and the maximum is at the leIt. (16.39) The minimum is conIirmed to be zero -- the plot seems to indicate that but the picture doesn't let us know whether it's really zero or just really small. Note again that this is the minimum value, it is not the location oI the minimum value. 16.6 One-step extrema-Iinding using maximize and minimize 333 minimize and maximize (16.40) Finding the maximum is a copy/edit job once we've worked out how to do the minimum. Sometimes, you want not only what the maximum or minimum value is, but also where it is. II you give maximi:e or minimi:e an extra third parameter, location, then it will return a sequence Ior a result. This sequence has a logical but somewhat intricate structure. You can use a chain oI selections to extract the location var location point Irom the answer given by Maple. Table 16.10: Solving a problem with minimize and maximize Solving a problem with minimize and maximize From Anton, Calculus 8th ed. p. 307 problem 13 (modiIied)
Find the absolute maximum and minimum values oI
Ior x in
Solution
(16.41) We deIine a Iunction. 334 16 Calculus and optimization Solving a problem with minimize and maximize We generate a plot to get an idea oI where to look Ior minima and maxima. Evidently the minimum is in the middle and the maximum is at the leIt. (16.42) We get the smallest value oI I in the interval. (16.43) (16.44) (16.45) (16.46) This is what minimize does with the extra parameter location. The result returned by minimi:e with this extra parameter contains not only the value oI the minimum, but all the values oI x where the minimum occurs. It takes a lengthy chain oI part-extraction operations to get the value out. 16.6 One-step extrema-Iinding using maximize and minimize 335 Solving a problem with minimize and maximize (16.47) (16.48)
(16.49) (16.50)
However, once we have Iigured it out, we can get the same result by daisy-chaining the operations together.
(16.51)
A copy/edit job will produce the similar sequence oI operations Ior the maximum. (16.52) (16.53)
Finding the maximum is a copy/edit job once we've worked out how to do the minimum. Table 16.11: Using optimization in a chemical production problem with minimize and maximize From Anton, Calculus 8th ed. p. 316-317 Example 7.
A liquid Iorm oI penicillin manuIactured by a pharmaceutical Iirm is sold in bulk at a price oI $200 per unit. II the total production cost (in dollars) Ior x units is
336 16 Calculus and optimization
and iI the production capacity oI the Iirm is at most 30,000 units in a speciIied time, how many units oI penicillin must be manuIactured and sold in that time to maximize the proIit? What will the revenue be at the maximal proIit? (16.54)
Solution
(16.55) (16.56) (16.57) We deIine a Cost, Revenue, and ProIit Iunction, using the inIormation given in the problem about cost, and the standard deIinitions Irom economics Ior revenue and proIit. We could use the proc.. end proc way oI deIining a Iunction to equal eIIect but the arrow notation was designed to make it convenient to enter these short deIinitions that don't need if or for.
We plot the proIit Iunction to scope out its behavior. Evidently the Iunction does hit a maximum, roughly around x20000. II we got x35 as the answer Irom our maximum calculation in Maple, we'd wonder iI we did things correctly.
16.7 One-step approximations to extrema using Optimization|Maximize| and Optimization|Minimize| 337
(16.58)
(16.59)
We are getting Iloating point answers Irom Maple because some oI the numbers in C are Iloating point. II we wanted an exact calculation, we would change the .003 into 3/1000.
We use the daisy-chaining oI operations we saw in the previous example to extract the value oI the x where the maximum is obtained. We use the floor Iunction which rounds down to the nearest integer. This is the way to guarantee that we have a result that is a whole integer, without Iractional part. ,The chemical process can't produce a Iraction oI a unit. (16.60) (16.61) (16.62) We used the clickable menu item "Numeric Formatting" (see Ior example the "A script that uses Iunctional composition" example in Chapter 8) to reIormat the result in terms oI currency.
16.7One-step approximations to extrema using Optimization]Maximize| and Optimization]Minimize| Maple's solve and fsolve provide exact and approximate solutions. In a similar Iashion, maximi:e and Optimi:ation[Maximi:e], and minimi:e and Optimi:ation[Minimi:e] provide exact and approximate solution to extrema problems.. Optimi:ation[Maximi:e] and Optimi:ation[Minimi:e] only work when there is a numerical answer. They use only numerical, not analytical knowledge about Iunctions. They produce a "best eIIort" approximation. The clickable interIace's "Optimization" operation invokes these approximate optimizers. Optimi:ation[Maximi:e] and Optimi:ation[Minimi:e] always return a list. The Iirst item oI the list is the extreme value, and the second item in the list is a list oI equations describing the location oI the extreme value. As with the exact optimizing Iunctions maximi:e and minimi:e, the second item can be used as a parameter to eval to evaluate an expression at the location oI an extreme value. While the inventiveness oI numerical analysts make such approximation techniques usually reliable, they can be Iooled and without warning produce a bad approximation. For that reason, the results oI fsolve, Maximi:e and Minimi:e should be checked against what else is known about the properties oI the actual solution. For example, by plugging the location oI the approximate maximum into the objective Iunction, does it really produce a value that is larger than any other value oI the objective Iunction that you can think oI? OIten times a plot makes this easy to tell. Table 16.12: Finding an approximation to the minimum with OptimizationMinimize] Anton, Calculus 8th ed. problem 47, p. 321 (modiIied)
Two particles, A and B, are in motion in the xv-plane. Their coordinates at each instant oI time t are given by
338 16 Calculus and optimization , , , . Find the minimum distance between A and B.
(16.63) (16.64) (16.65) (16.66)
(16.67) (16.68) (16.69) (16.70)
p1 and p2 are lists oI the x and y positions Ior each point.
dist is the objective Iunction. This is the Euclidean distance between the two points. We can compute the distance between p1 and p2 using it.
16.7 One-step approximations to extrema using Optimization|Maximize| and Optimization|Minimize| 339 It's always good to have an independent way oI evaluating the answer you get Irom a "solver". In this case, we can plot the Iunction and Irom that see approximately where the answer ought to be. Our Iirst plot does not show the minimum that clearly, so we do another plot that emphasizes the region oI interest. (16.71) Using with, we can then say Minimize rather than Optimization|Minimize|.
340 16 Calculus and optimization (16.72)
The exact location is t 0.4, but the rounding error made during the operation oI Minimize leads to only an approximation oI the exact answer. This is typical. (16.73) (16.74) (16.75) According to the structure returned by this Iunction, the location inIormation is in the second element oI the result.
We can Iind the location oI particles A and B at t0.4 by evaluating the expression p1 and p2 at that value oI t. Note that minLocation is a list consisting oI an equation, which eval can use as its second argument. (16.76) (16.77)
This is a problem that Maple's exact solver can solve exactly. The numerical approximation produced by Optimization|Minimize| is in close agreement with the exact result. (16.78) This expression has a complicated expression Ior the exact minimum. We could try to approximate it using the right-click- ~approximate menu, or we could give it to the approximate minimizer instead. 16.7 One-step approximations to extrema using Optimization|Maximize| and Optimization|Minimize| 341 (16.79) (16.80) (16.81)
Table 16.13: An example where the approximate minimizer gets fooled (16.82)
While the approximate solvers will probably Iare well on most Iunctions that have only a Iew extrema, they can be Iooled iI the Iunction has a lot oI extrema close to each other. In that case, it may return something that is an extremum in a small neighborhood around the point, but not iI a larger interval is considered. This "tricky" example is Irom Cheney and Kincaid's textbook on numerical analysis, Numerical 342 16 Calculus and optimization mathematics and computing, 6th edition, 2008 Thomson Brooks/Cole, p.626. (16.83)
We get an answer Irom approximation technique. There are no error or warning messages. To check this answer, let's do a plot and see what the Iunction looks like.
We see why an approximate solver might have problems -- there are lots oI "local minima". x.56 does not seem to be a true minimum Ior in the interval. We can draw a zoomed in plot and look closer: 16.7 One-step approximations to extrema using Optimization|Maximize| and Optimization|Minimize| 343
It's clear now that x0.56 is not the location oI the minimum. x's value should be about x-0.02 and the minimum value is about -1. These approximate coordinates were Iound using the cursor positioning Ieatures described in Table XX. (16.84) (16.85)
Applying the exact minimizer to this problem produces a hard to understand result that takes much more time to compute than the approximate technique. Nevertheless, it is the true minimum in the interval. We ask evalf to approximate it. That produces something that, while still approximate, agrees more with what the plot leads us to expect Ior the right answer.
The moral: numerical optimization typically produces results quickly but even the best can be Iooled. You need to veriIy the results iI the cost oI making an error is high. We might be tempted to see iI we can change the circumstances so that the objective Iunction we work with is not so "squirrelly". 344 16 Calculus and optimization 16.8Multivariate operations in Maple diff , minimi:e, solve, and the rest can handle problems and situations where there are multiple variables involved. Approximation methods (e.g. fsolve or Optimization|Maximize| oIten take more prominence with multivariate problems because oI the diIIiculty and/or expense oI Iinding oI succinct Iormulas that express the solution. We won't explore Maple's abilities to handle multivariate problems here, but they are there to be explored and used when you're ready Ior it. Table 16.14: Multivariate operations in Maple (16.86)
Compute the second partial derivative with respect to x.
(16.87)
The textual way oI entering partial derivatives. (16.88) (16.89)
We are interested in Iinding the points oI intersection with the unit circle with center at (0,0), and the line deIined by xy5. Doing it exactly gives an answer, but it's not easy to understand -- x and y can be either the positive or negative solution to a quadratic expression. Introducing a Iloating point number into the equation (1.25 instead 10/8) tells solve that it's all right to approximate the results. 16.8 Multivariate operations in Maple 345 (16.90) (16.91)
(16.92) Warning, computation interrupted (16.93)
We want to Iind the minimum value oI an expression in two variables. minimi:e takes a long time to work and doesn't seem to come up with much. However, the approximate minimizer Iinds a value oI 5. Multivariate plotting is handled by the plot3d Iunction. By clicking on the plot window, the point oI view can be moved or rotated. Animations, etc. can be built in a Iashion similar to two dimensional plots. 346 16 Calculus and optimization
16.9Chapter summary Symbolic differentiation using the expression palette, right- click, control-.
Enter the expression, and then right-click (control-click on Macintosh) to bring up the calculation options. Select diIIerentiate-~x
We can calculate the second derivative with respect to t oI this expression by perIorming diIIerentiation twice. We simpliIy the expression a bit by perIorming the operation simpliIy- ~symbolic.
II we want the document to display the mathematical notation Ior the derivative, we can select Irom the expression palette and then Iill in the slots f and x. We can then get Maple to calculate the derivative by typing control-. Symbolic differentiation and evaluation of derivatives, textually
Example Commentary (16.94) (16.95) (16.96) (16.97) (16.98)
Find the Iirst derivative oI the expression with respect to x.
Find the Iirst derivative oI the expression with respect to t.
Find the second derivative oI the expression with respect to t. The result is the same as iI we had taken the derivative oI 1.2.4.
diffs second argument must be the variable oI diIIerentiation. Note that iI the variable doesn't occur in the expression, the 16.9 Chapter summary 347 (16.99)
(16.100)
(16.101)
(16.102) derivative (according to the mathematical deIinition) is zero. II you are surprised by getting a zero derivative, check that you are using the correct variable to diIIerentiate with respect to.
simplifv can reduce the size oI the expression, although factor or expand sometimes work better. Sometimes additional trigonometric identities need to be applied, through simplifv(...., trig).
This is a way to compute .
This is a way to compute The result oI evaluation does not have to be a number even iI a numeric value is being supplied Ior one oI the variables in the expression being evaluated. Textual version of limits Example Commentary
(16.103)
The Iirst argument is the expression that you wish to take the limit oI. The second argument is an equation indicating the limit variable and the limiting value.
You can use "inIinity" or "-inIinity" as the way oI speciIying or - textually without use oI the palette. 348 16 Calculus and optimization
(16.104)
(16.105)
(16.106)
The third optional third argument to limit can speciIy a one sided limit. This is the textual way oI speciIying . There is no simple way oI speciIying this
This is the textual way oI speciIying . Minima and maxima Operation Example Exact minimum or maximum value Ior x in
Solution
(16.107)
It's usually a good idea to plot the objective Iunction to get some sense oI where the extrema are. Remember that the Iunction to be 16.9 Chapter summary 349 investigated should be continuous iI you expect good results Irom calculus techniques.
(16.108) (16.109)
Exact minimum or maximum value location (16.110) (16.111)
Evaluation oI an Iunction at an extremum point Evaluate g at the location of the smallest value of f. (16.112) (16.113) (16.114)
Evaluation oI an expression at an extremum point (16.115) 350 16 Calculus and optimization (16.116) (16.117)
Approximate minimum or maximum value and location (16.118) (16.119) (16.120) (16.121) Remember that numerical methods can be fooled into returning answers that are seriously incorrect. Verify your computed results using other techniques. Plots can often indicate that something is weird, although even that is not foolproof. More mathematical modeling: area-finding, piecewise expressions, and splines Chapter Overview We introduce three more computational features from Maple's built-in library: Computing definite and indefinite integrals Piecewise expressions Curve fitting using splines Many scientific or engineering problems benefit from the use of these mathematical concepts. Recalling basic facts about integration We review some of the basic facts and terminology about integration from your calculus courses. Definite integration can be related to finding the area under a curve described by a function. The definite integral a b f x dx is notation for this. If an answer for a definite integration problem exists, then it is a number which could be described exactly or as an approximation. Indefinite integration is sometimes called the problem of antidifferentiation: given a function f, find another function F whose derivative is f: d dx F x = f x . Another way of writing this relationship is: f x dx = F x . In most cases, there is no single function F(x) that solves the antiderivative problem for f(x). There is a whole family of functions that differ from each other by a constant. Sometimes the antiderivative F(x) is written with an extra symbolic constant: f x dx = F x CC, particularly if antidifferentiation is going to be applied as only one step of a problem-solving process. Since the hard part of doing indefinite integration is finding F(x) without the constant and since the name of the constant can be freely chosen, systems that can compute antiderivatives often omit the constant in their answers, letting the user add in the constant of their choice later if they want to. The answer F(x) is expected to be a formula involving expressions and functions that the user already knows about. F(x), when it exists, is referred to as a closed form solution to the integration problem or the antiderivative of f(x). For calculus freshmen, these are expressions that involve numbers, polynomials, roots, rational functions, trig, logarithm and exponential functions. For more advanced mathematics students, it might include other functions: erf (error function), Bessel, G, etc. The Fundamental Theorem of Calculus (FTC) states that the definite integral can computed if the antiderivative is known: a b f x dx = F b KF a , where F is any function such that d dx F x = f x . Programs for doing indefinite integration/antidifferentiation have been around from the early '60s. They can be found in a number of symbolic systems: Maple, Mathematica, Macsyma (now found in SAGE), and MuPad (now part of Matlab). It is not an easy program to write. Even today in the era of "open source", the quality and power of such programs varies significantly. The ideas for how to program an indefinite integrator comes from seminal work done by Robert Risch in the late 1960s, who was in turn continuing work done previously by other mathematicians such as Joseph Liouville (1809-1882). Earlier approaches in the early '60s treated symbolic anti- differentiation as a problem in artificial intelligence. Those AI programs (such as SAINT by James Slagle (1934-1994) and SIN by Joel Moses (1941-) tried to simulate the expertise of a college calculus student. However, they would sometimes give up on problems that could be solved through a clever trick of substitution or other reformulation. Risch's work used advanced mathematics to come up with programs that would guarantee that they could find a solution if there was one to be found, for certain classes of integrands. However, while programs using Risch's techniques are more powerful, they don't necessarily give the answer in simplest terms as a mathematics textbook would. That may require more symbolic manipulation, under human guidance. Indefinite integration Doing anti-differentiation with (1.3.1.4) (1.3.1.4) (1.3.1.1) (1.3.1.1) (1.3.1.2) (1.3.1.2) (1.3.1.3) (1.3.1.3) (1.3.1.5) (1.3.1.5) Indefinite integration with int The clickable interface can be used to input an indefinite integration problem for Maple to compute. Use the f dx item in the Expression Palette, then edit the expression f and the variable of integration x. This computes the antiderivative of the expression, with respect to the variable of integration. The general form of the textual version of the integration command is int( expression , var ) Indefinite integration with int Example! Commentary 1 x dx ln x cos x 2 dx 1 2 cos x sin x C 1 2 x cos 2 x dx 1 2 cos x sin x C 1 2 x The clickable interface can be used to enter the integration problem. In the clickable interface there are two ways of entering what is "cos x times cos x ". int sqrt x , x 2 3 x 3 / 2 int cos a $sin a 2 , a K 1 3 cos 3 2 a Ccos 1 2 a The textual form of integration works in the same way. This uses the textual form of the command in a small script. The script computes the symbolic integral and stores it as the value of the variable i1. Then it takes the derivative of i1 and assigns that to d1. According to the Fundamental Theorem of (1.3.1.4) (1.3.1.4) (1.3.1.1) (1.3.1.1) (1.3.1.2) (1.3.1.2) (1.3.1.3) (1.3.1.3) (1.3.1.5) (1.3.1.5) expr := tan(t) + x^2; i1 := int(expr,t); d1 := diff(i1,t); difference := d1-expr; printf("difference: %a\n", difference); printf("simplified difference: %a\n", simplify(difference)); tan t Cx 2 Kln cos t Cx 2 t sin t cos t Cx 2 sin t cos t Ktan t difference: sin(t)/cos(t)-tan (t) simplified difference: 0 Calculus, d1 should be the same as expr. However, we have to get Maple to simplify the difference in order to have it actually be reduced to zero, using the built-in library procedure simplify. Understanding the answers from int If Maple does not know how to find an answer it will return an expression that is the display version of the input expression. It does this instead of giving an error message or NULL so that a script or program using integration can continue even if the attempt to integrate fails. For example, even if you don't have the anti-derivative of the integrand, you can still try to do an approximate numerical definite integration. We discuss that in section 20.4. Sometimes the answer given by the symbolic integrator will be given in terms of functions that beginning students haven't heard of. This can be confusing, but unfortunately most systems written for professionals to use do not have a "beginners mode" that avoids using advanced math. If you see a function you don't know of, you can get a brief explanation of it through on- line help. Whether or not the answer computed for you is satisfactory depends on the situation. A strange-looking answer might be a sign that you may have mis-entered the problem ("garbage in, garbage out"). It might mean that there's a way to simplify the strange-looking answer into something you recognize. If the answer involves functions you haven't heard of, it may mean that it's time to learn more math to deal with the situation. To summarize, the responsibilities that users of symbolic integration programs have are a) to be prepared to learn about more advanced functions if answer is of that form, b) understand when the computer system is saying that it can't find a closed form solution. Integration answers using advanced functions e x 2 dx K 1 2 I p erf I x (1.3.2.1) You wouldn't see this integration problem in an elementary calculus textbook, because the answer involves the "error function". The term "error function" is not indication that there is a mistake, It's the official terminology for the function, in the same way that "sine", "cotangent" or "exponential" are names of functions. The name arose from the function's original use in probability and statistics. You can read more about the error function by typing "erf" or "error function" into Maple's on-line help. Integration answers when Maple can't find an expression for the anti-derivative answer d int f x , x f x dx (1.3.2.2) answer2 := int(g(t),t); printf("The answer was: %a",answer2); g t dt The answer was: int(g(t),t) Maple can't find the antiderivative because we haven't told it what the function f is. It can't find the symbolic integral for g either, for the same reason. We see that printf says that the value of answer2 is, in textual form, the same as the input was. int 1 / sqrt log sin x C1 Cexp x , x 1 ln sin x C1 Ce x dx (1.3.2.3) Here's another example of an integral that Maple can't do even though the expression being integrated is something that it recognizes. 1. 1. (1.3.3.5) (1.3.3.5) 3. 3. (1.3.3.9) (1.3.3.9) (1.3.3.11) (1.3.3.11) (1.3.3.7) (1.3.3.7) (1.3.3.10) (1.3.3.10) (1.3.3.12) (1.3.3.12) (1.3.3.2) (1.3.3.2) (1.3.3.3) (1.3.3.3) (1.3.3.8) (1.3.3.8) 2. 2. (1.3.3.13) (1.3.3.13) (1.3.3.1) (1.3.3.1) (1.3.3.6) (1.3.3.6) (1.3.3.4) (1.3.3.4) Checking that your integration answer is correct Like everything else produced by a computer, it's still your responsibility to verify that the computed answer is correct. After all, even if you think it unlikely that there's a programming error in int's programming, you might have mis-entered the function you want to integrate. However, it's easy to use Maple to check integration answers it provides: Is the derivative of your answer the same or equivalent to what you started with? Because of the relationship between integration and differentiation, it is possible to check integration answers without having to do the integration by hand: Use int to calculate the answer Apply diff to the answer. The result of differentiation should be the function you were originally tried to integrate with int. If the derivative does not look the same as the integrand, try simplify on the difference between the result of step 2 and the original expression. If you get zero, the two are equivalent. Checking answers Example Commentary expr d 1 C x C cos x 2 1 Cx C 1 2 cos x answer d int expr, x x C 1 2 x 2 C 1 2 sin x dAnswer d diff answer, x 1 Cx C 1 2 cos x expr KdAnswer 0 The derivative of the symbolic integral is the same as the original expression. This is obvious just by "eyeballing" it, but we can also confirm that the difference between expr and the derivative is 0. expr d sin x 2 sin x 2 answer d int expr, x K 1 2 cos x sin x C 1 2 x dAnswer d diff answer, x 1 2 sin x 2 K 1 2 cos x 2 C 1 2 The derivative of the symbolic integral does not appear at first glance to be the same as the original expression. However, the difference between them does simplify to zero, so they are equivalent. Maple does not automatically employ trig identities such as sin 2 a Ccos 2 a = 1 because it would often introduce tedious delay to try to apply all possible identities all the time. (1.3.3.5) (1.3.3.5) (1.3.3.10) (1.3.3.10) (1.3.4.5) (1.3.4.5) (1.3.3.3) (1.3.3.3) (1.3.4.10) (1.3.4.10) (1.3.3.8) (1.3.3.8) (1.3.3.13) (1.3.3.13) (1.3.4.12) (1.3.4.12) (1.3.4.3) (1.3.4.3) (1.3.4.9) (1.3.4.9) (1.3.4.6) (1.3.4.6) (1.3.4.15) (1.3.4.15) (1.3.4.4) (1.3.4.4) (1.3.3.9) (1.3.3.9) (1.3.3.11) (1.3.3.11) (1.3.3.7) (1.3.3.7) (1.3.4.7) (1.3.4.7) (1.3.4.11) (1.3.4.11) (1.3.4.1) (1.3.4.1) (1.3.3.12) (1.3.3.12) (1.3.3.2) (1.3.3.2) (1.3.4.2) (1.3.4.2) (1.3.3.1) (1.3.3.1) (1.3.3.6) (1.3.3.6) (1.3.4.14) (1.3.4.14) (1.3.3.4) (1.3.3.4) (1.3.4.8) (1.3.4.8) (1.3.4.13) (1.3.4.13) d dexpr KdAnswer 1 2 sin x 2 C 1 2 cos x 2 K 1 2 simplify d 0 expr d x^2 C1 / xK1 x 2 C1 x K1 answer dint expr, x 1 2 x 2 Cx C2 ln x K1 dAnswer d diff answer, x x C1 C 2 x K1 simplify expr KdAnswer 0 Here is another example of a symbolic integration answer whose derivative does not appear to be the same as the starting expression. However, simplification of the difference between the two indicates that the two are equivalent because their difference simplifies to zero. Sometimes the "simplify the difference to zero" trick is not needed to check work because it is obvious that the two are the same. Maple has other simplification operations such as normal, factor, convert, combine, and expand that will attempt to put results into alternative forms. See on-line help about simplify and the other operations for more information. Troubleshooting int for indefinite integration problems int is intended to work with expressions involving the variable of integration, not names of functions. If an expression does not seem to involve the variable of integration, it is treated as a symbolic constant, regardless of whether it is also the name of a function. This can lead to misleading "answers" Variables assigned expressions work with int, but not variables assigned function definitions badResult d cos dt cos t Since the integrand is just cos, and does not involve the variable of integration, Maple treats it as a symbolic constant. Since for a name a, a dt = a t the result of this integral is the name "cos", times t. It sort of looks like cos(t) but it isn't. (1.3.4.5) (1.3.4.5) (1.3.4.10) (1.3.4.10) (1.3.4.12) (1.3.4.12) (1.3.4.3) (1.3.4.3) (1.3.4.9) (1.3.4.9) (1.3.4.6) (1.3.4.6) (1.3.4.15) (1.3.4.15) (1.3.4.4) (1.3.4.4) (1.3.4.7) (1.3.4.7) (1.3.4.11) (1.3.4.11) (1.3.4.1) (1.3.4.1) (1.3.4.2) (1.3.4.2) (1.3.4.14) (1.3.4.14) (1.3.4.8) (1.3.4.8) (1.3.4.13) (1.3.4.13) eval badResult, t = 0 0 eval badResult, t = .5 0.5 cos One way to demonstrate that this answer isn't cos(t) is to evaluate it at t=0. 0$cos = 0. That certainly isn't the value of cos(0). Evaluating this expression for another value indicates that Maple's integration result is actually "t*cos": the variable t times the name of a function. goodResult d cos t dt sin t eval goodResult, t = 0 0 eval goodResult, t = .5 0.4794255386 Giving the symbolic integrator an expression involving the variable t gives the desired result. g d x / x^2 x/x 2 int g, x g x Another mistaken attempt to integrate a function name instead of an expression involving the integration variable. Like the example above, it produces the answer "g times x". Note that the value of g is not the expression x^2, it's the function definition x -> x^2. int g x , x 1 3 x 3 int g t , t 1 3 t 3 Evaluating g(x) does produce x 2 , which int can integrate properly. Evaluate g(t) produces an expression in t, which int can integrate properly if it is given t as the variable of integration. int g y , x y 2 x This is the integral of y 2 with respect to x, which is x times y 2 . int abs b , b K 1 2 b 2 b %0 1 2 b 2 0 !b Integrating the absolute value function returns a piecewise expression. We talk more about piecewise expressions in Section 20.6. (1.3.4.5) (1.3.4.5) (1.3.4.10) (1.3.4.10) (1.3.4.12) (1.3.4.12) (1.3.4.3) (1.3.4.3) (1.3.4.9) (1.3.4.9) (1.3.4.6) (1.3.4.6) (1.3.4.15) (1.3.4.15) (1.3.4.4) (1.3.4.4) (1.3.4.7) (1.3.4.7) (1.3.4.11) (1.3.4.11) (1.3.4.1) (1.3.4.1) (1.3.4.2) (1.3.4.2) (1.3.4.14) (1.3.4.14) (1.3.4.8) (1.3.4.8) (1.3.4.13) (1.3.4.13) procAbs d proc x if x R0 then return x else return Kx end if; end proc x if 0 != x then return x else return Kx end if end proc int procAbs b , b Error, (in procAbs) cannot determine if this expression is true or false: 0 <= b We write a Maple procedure to emulate the absolute value function... We can't integrate this procedure because the if statement gives an error when it tries to decide whether x is greater than zero when there is no numerical value for x. procNew d proc x eval exp x $a, a = 2$x end proc x eval exp x * a, a = 2 * x end proc int procNew y C1 , y 2 e y C1 y Maple can integrate the results of procedures, as long as the procedure can execute with symbolic-valued parameters. This computes the integral of exp(y+1)*(y+1) . Note that we could use it to calculate the integral of exp(z)*2*z, exp(w)*2*w, etc. in a similar fashion. Definite integration Definite integration with int (1.4.9) (1.4.9) (1.4.8) (1.4.8) (1.4.10) (1.4.10) (1.4.6) (1.4.6) (1.4.1) (1.4.1) (1.4.11) (1.4.11) (1.4.2) (1.4.2) (1.4.12) (1.4.12) (1.4.5) (1.4.5) (1.4.4) (1.4.4) (1.4.3) (1.4.3) (1.4.7) (1.4.7) To use the clickable interface to calculate a definite integral, use the a b f dx item in the Expression Palette, then edit the expressions f, a, and b, and the variable of integration x to suit your problem. If the answer to a definite integration problem returns as the symbolic answer, then doing evalf( ... ) of it will produce an approximation to the area,. These approximation techniques do not require the use of symbolic integration to find the answer. Approximation techniques will be used automatically, without evalf, if the integrand or the limits of integration involve floating point numbers rather than exact fractions. The general form of the textual version of the command is int( expression , var = a..b ) Definite Integration Examples Example Commentary Anton, Calculus 8th ed. problem 6..5.14. Calculate K10 5 6 dt , K p 3 p 3 sin x dx, 0 3 x K2 dx , 0 2 4 Kx 2 dx . K10 5 6 dt 90 Using the clickable interface. int sin x , x =K p 3 .. p 3 0 Using the document interface but with the textual form of the operation. 0 3 x K2 dx 5 2 Using the clickable interface again. Entry of the operation within a code (1.4.9) (1.4.9) (1.4.8) (1.4.8) (1.4.10) (1.4.10) (1.4.6) (1.4.6) (1.4.1) (1.4.1) (1.4.11) (1.4.11) (1.4.2) (1.4.2) (1.4.12) (1.4.12) (1.4.5) (1.4.5) (1.4.4) (1.4.4) (1.4.3) (1.4.3) (1.4.7) (1.4.7) result := int(sqrt(4-x^2),x=0..2); p edit region, followed by its execution with control (command)-E Anton problem 32 (a). Calculate K3 3 x 2 K1 K 15 x 2 C1 dx . Answer should be 30* arctan(13/9) + 28/3. int abs x^2 K1 K15 / x^2 C1 , x =K3 ..3 28 3 K30 arctan 3 C60 arctan 2 simplify (1.4.4) 30 arctan 13 9 C 28 3 The original form of the answer given by Maple does not match the answer key, but fortunately the simplify function reduces the result to the desired form. Anton problem 32 (b). Calculate 0 3 2 1 1 Kx 2 K 2 dx using Theorem 6.5.5, which states that for a !b !c, a c f x dx = a b f x dx C b c f x dx . You will find it necessary to choose a good splitting point -- try plotting the function and finding where it is zero. expr dabs 1 / sqrt 1Kx^2 Ksqrt 2 1 1 Kx 2 K 2 int expr, x = 0 ..sqrt 3 / 2 Integration is a domain where even the best programs may not be able to find the answer. It usually doesn't hurt to see if Maple's software can find the answer by itself. But we see here that since the result is the same as the input, that Maple can't do the problem without help. (1.4.9) (1.4.9) (1.4.8) (1.4.8) (1.4.10) (1.4.10) (1.4.6) (1.4.6) (1.4.1) (1.4.1) (1.4.11) (1.4.11) (1.4.2) (1.4.2) (1.4.12) (1.4.12) (1.4.5) (1.4.5) (1.4.4) (1.4.4) (1.4.3) (1.4.3) (1.4.7) (1.4.7) 0 1 2 3 1 1 Kx 2 K 2 dx plot expr, x = 0 ..sqrt 3 / 2 x 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.1 0.2 0.3 0.4 0.5 Plotting the function suggests that there's quite a change occurring around 0.7. This point is probably the splitting point that the problem is suggesting we find. But what is it, exactly? zeroes dsolve expr = 0 , x x = 1 2 2 , x = K 1 2 2 splitPt d zeroes 2 x = K 1 2 2 bpt d eval x, (1.4.9) K 1 2 2 Giving solve the problem of where the function is zero gives us two solutions. One is negative and we don't care about it since our definite integral is looking at the function only between 0 and 3 2 . We use the splitting idea to ask Maple to evaluate two definite integrals. It can (1.4.9) (1.4.9) (1.4.19) (1.4.19) (1.4.16) (1.4.16) (1.4.14) (1.4.14) (1.4.8) (1.4.8) (1.4.10) (1.4.10) (1.4.6) (1.4.6) (1.4.1) (1.4.1) (1.4.11) (1.4.11) (1.4.2) (1.4.2) (1.4.12) (1.4.12) (1.4.5) (1.4.5) (1.4.18) (1.4.18) (1.4.17) (1.4.17) (1.4.13) (1.4.13) (1.4.4) (1.4.4) (1.4.3) (1.4.3) (1.4.7) (1.4.7) (1.4.15) (1.4.15) 0 bpt expr dx C bpt 3 2 expr dx 1 4 p K1 C K 1 2 2 1 2 3 1 1 Kx 2 K 2 dx do each piece. We predict that within 20 years Maple or similar systems will be able to do this problem completely on their own without this kind of manual analysis and manipulation. Anton Example 4, ch. 8 Evaluate KN N 1 1 Cx 2 dx KN N 1 1 Cx 2 dx p Maple can do improper definite integrals since it can do symbolic limits (e.g. the functionality available through limit). You can input infinity by through the Common Symbols Palette that can be found on the left hand side of the Maple application window. Anton Example 6 (c) Ch 8. Evaluate 0 N 1 x $ x C1 dx answer := int(1/(sqrt(x)*(x+1)), x = 0 .. infinity); p Infinity is can also be input textually as the symbol . If the coefficients or limits of integration are floating point numbers, then Maple may use alternative techniques to approximate the integral. These approximations are often good and sometimes work when the exact techniques do not. Numerical approximation of definite integration Maple is unable to calculate the exact solution (1.4.19) (1.4.19) (1.4.16) (1.4.16) (1.4.14) (1.4.14) (1.4.18) (1.4.18) (1.4.17) (1.4.17) (1.4.13) (1.4.13) (1.4.15) (1.4.15) result dint exp x 2 log x 2 , x = 2 ..3 2 3 e x 2 ln x 2 dx to this definite integration problem. evalf result 694.1492846 evalf of the expression for the integral will invoke a numerical approximation technique. It says that the area is approximately 694.15. int exp x 2 log x 2 , x = 2 ..3.0 694.1492846 The difference between this and the original input is that the upper limit of integration has changed from "3" to "3.0". Because this is a floating point number, Maple will use numerical approximation automatically. int exp x 2 log x 2 , x = 1 ..3 1 3 e x 2 ln x 2 dx evalf (1.4.16) Float N This is the same integrand, but the lower limit of integration has been changed to a point where the integrand is infinite. Not surprisingly, the numerical approximation method doesn't give us a number for the answer. Since the approximation method doesn't guarantee that its answer is close to the actual answer, this result doesn't prove that the area under the curve is infinite. Further analysis by a mathematician would be needed to establish this conclusively. int x 6 C2$x C1 x 3 C2$x 2 C1 , x = 0 ..1 K > _R= RootOf _Z 3 C2 _Z 2 C1 1 _R 3 _RC4 2 5 K_R C10 _R 2 ln K_R K 89 12 int finds a symbolic solution to the integral, but it's not that enlightening. A mathematician might find this answer useful, but the typical user will prefer a numerical approximation. We can get that either by applying evalf to the result, or by using int with a floating point number as one of the limits of integration. (1.4.19) (1.4.19) (1.4.16) (1.4.16) (1.4.14) (1.4.14) (1.5.1) (1.5.1) (1.5.2) (1.5.2) (1.5.4) (1.5.4) (1.5.5) (1.5.5) (1.4.18) (1.4.18) (1.5.3) (1.5.3) (1.4.17) (1.4.17) (1.4.13) (1.4.13) (1.4.15) (1.4.15) C > _R= RootOf _Z 3 C2 _Z 2 C1 1 _R 3 _RC4 2 5 K_R C10 _R 2 ln 1 K_R int x 6 C2$x C1 x 3 C2$x 2 C1 , x = 0 ..1.0 1.161103706 Arc-length integration Recall the following information about the arc length of parametric curves (Anton, ch 7.4, theorem 7.4.3). If no segment of the curve represented by the parametric equations x = x t , y = y t , a %t %b is traced more than once as t increases from a to b, and if dx dt and dy dt are continuous functions for a %t %b, then the arc length L of the curve is given by L = a b dx dt 2 C dy dt 2 dt . We can use this formula and Maple's definite integration operation to calculate arc length easily. Maple has an arclength operation built into its "Student1" package: Calculating arclength Student[Calculus1][Arclength]([ x expression, y expression], parameter = a..b) calculates the arclength of a curve described by the parametric expressions in the two coordinates. The package uses the definite integration feature of Maple. Therefore, it will use approximate methods if a, b, or any number in the expressions is a floating point number. Student[Calculus1][Arclength](f(x), x = a..b); calculates the arc of the curve given by the parameterization x=t, y=f(t) (1.5.1) (1.5.1) (1.5.4) (1.5.4) (1.5.5) (1.5.5) (1.5.3) (1.5.3) (1.5.2) (1.5.2) Solving a problem involving arclength Problem 11, section 7.4 Anton p. 489: Let the parameterization be x = cos 2$t , y =sin 2$t , 0 %t % p 2 . Find the arclength. plot cos 2$t , sin 2$t , t = 0 .. p 2 , scaling = constrained K1 K0.5 0 0.5 1 0.2 0.4 0.6 0.8 1 Student Calculus1 ArcLength cos 2 * t , sin 2 * t , t = 0 ..p / 2 p This is a parametric plot (see this section). We say scaling =constrained so that the x and y axes are given the same scaling. Student Calculus1 ArcLength cos 2 * t , sin 2 * t , t = 0 ..p / 2.0 3.141592654 The use of "2.0" makes Maple use approximation techniques in the arclength calculation. (1.5.1) (1.5.1) (1.5.4) (1.5.4) (1.5.5) (1.5.5) (1.5.3) (1.5.3) (1.5.2) (1.5.2) npExpr d sqrt 1 Kx 2 1 Kx 2 plot npExpr, x =K1 ..1, scaling = constrained x K1 K0.5 0 0.5 1 0.2 0.4 0.6 0.8 1 This is an alternative formulation for the same curve, as the plot indicates. We load in the Student Calculus1 package using with. Then we can just use ArcLength instead of the full name of the library procedure. with Student Calculus1 AntiderivativePlot, AntiderivativeTutor, ApproximateInt, ApproximateIntTutor, ArcLength, ArcLengthTutor, Asymptotes, Clear, CriticalPoints, CurveAnalysisTutor, DerivativePlot, DerivativeTutor, DiffTutor, ExtremePoints, FunctionAverage, FunctionAverageTutor, FunctionChart, FunctionPlot, GetMessage, GetNumProblems, GetProblem, Hint, InflectionPoints, IntTutor, Integrand, InversePlot, InverseTutor, LimitTutor, MeanValueTheorem, MeanValueTheoremTutor, NewtonQuotient, NewtonsMethod, NewtonsMethodTutor, (1.5.4) (1.5.4) (1.6.3) (1.6.3) (1.5.5) (1.5.5) (1.5.3) (1.5.3) (1.6.2) (1.6.2) (1.5.1) (1.5.1) (1.6.4) (1.6.4) (1.6.1) (1.6.1) (1.5.2) (1.5.2) PointInterpolation, RiemannSum, RollesTheorem, Roots, Rule, Show, ShowIncomplete, ShowSolution, ShowSteps, Summand, SurfaceOfRevolution, SurfaceOfRevolutionTutor, Tangent, TangentSecantTutor, TangentTutor, TaylorApproximation, TaylorApproximationTutor, Understand, Undo, VolumeOfRevolution, VolumeOfRevolutionTutor, WhatProblem ArcLength npExpr, x =K1 ..1 p Piecewise expressions and piecewise functions Mathematical situations sometimes need functions that have more than one part to their definition. Consider the following expression: a d - x x !0 x x R0
This defines a piecewise expression. It means "-x if x is less than 0, x if x is R 0." Piecewise expressions Example Commentary a d - x x !0 x x R0
Kx x !0 x 0 %x Define a piecewise expression. It means "-x if x is less than 0, x if x is R 0." plot a, x =K5 ..5 Plot the piecewise expression for x in the range -5..5. (1.6.6) (1.6.6) (1.6.3) (1.6.3) (1.6.2) (1.6.2) (1.6.4) (1.6.4) (1.6.5) (1.6.5) (1.6.1) (1.6.1) x K4 K2 0 2 4 1 2 3 4 5 b d piecewise x !0, Kx, x R0, x Kx x !0 x 0 %x b is assigned the same piecewise expression, using the textual way of entering the information. bMinus1 d simplify 2$ b K1 K1 K2 x x !0 K1 C2 x 0 %x Maple can do limited algebra on piecewise expressions. eval bMinus1, x = 3 5 Since x is greater than or equal to 0, the bottommost piece of the expression applies, and the result of evaluation is K1 C2$3 = 5. We can provide more branches to a piecewise expression. In the Palette version, you can add an extra row by typing control-shift-R (on Macintosh, command-shift-R) in the bottom row. In the textual version, you can add extra items onto the sequence of inputs to the function. More extensive piecewise expressions with the clickable and textual interfaces Clickable interface Commentary c d 1 x !K1 2 1 O x RK1 5 x R1 / To get this we typed c :=, then selected the - x x !a x x Ra item from the palette. We edited what was there. Then we typed control-shift-R and filled in the bottom row. After completing the piecewise expression, we right-clicked (control-clicked in Mac) the expression and (1.6.6) (1.6.6) (1.6.5) (1.6.5) x K10 K5 0 5 10 2 3 4 5
selected the 2D plot item from the popup menu. Textual interface step2 d piecewise x !K1, 1,K1 %x !2, x 2 , x R2, x 3 1 x !K1 x 2 K1 %x and x !2 x 3 2 %x plot step2, x =K2 ..4 x K2 K1 0 1 2 3 4 10 20 30 40 50 60 eval step2, x = 1.5 2.25 This is an expression with three pieces that fit together at -1, and 2. To get the %, we typed the characters <= consecutively. Maple automatically reset them as the mathematical symbol %. This uses the plot facility using the textual interface. (1.6.6) (1.6.6) (1.6.8) (1.6.8) > > (1.6.5) (1.6.5) (1.6.7) (1.6.7) > > We can evaluate the expression at x=1.5. Since the input is limited-precision and the expression can be completely evaluated using arithmetic, we get a limited-precision result. It is possible to use otherwise as one of the clauses of a expression. Usually there are an even number of inputs to , but if there is an odd number, then the last input is the "otherwise" value. More extensive piecewise expressions with the clickable and textual interfaces Clickable interface Commentary c d 1 K2 ! x !K1 2 1 O x RK1 5 otherwise 1 K2 !x and x !K1 2 x !1 and K1 %x 5 otherwise / smartplot (1.6.7) x K10 K5 0 5 10 2 3 4 5
To get this we typed c :=, then selected the - x x !a x x Ra item from the palette. We edited what was there. Then we typed control-shift- R and filled in the bottom row. After completing the piecewise expression, we right- clicked (control-clicked in Mac) the expression and selected the 2D plot item from the popup menu. Textual interface Commentary (1.6.10) (1.6.10) (1.6.8) (1.6.8) (1.6.9) (1.6.9) > > (1.6.11) (1.6.11) (1.6.12) (1.6.12) (1.6.7) (1.6.7) > > (1.6.14) (1.6.14) (1.6.13) (1.6.13) step3 d piecewise K2$p %x %p, sin x , p !x !5, 0,K2 sin x K2 p %x and x %p 0 p !x and x !5 K2 otherwise plot step3, x =K10 ..10 x K10 K5 0 5 10 K2 K1 1 We define an expression that is sin(x) for x between K2$p and p, 0 between p and 5, and -2 everywhere else. If the number of terms in the sequence of inputs to piecewise is odd, then the last term is the "otherwise" clause. Since a piecewise expression is still an expression, we can use it as part of a function definition. Within a function definition, a piecewise expression can be used instead of an if then ... end if. More piecewise function definitions and uses Clickable interface Commentary h dx/ x x !1.5 x$log x x R1.5 x/piecewise x !1.5, x, 1.5 %x, x log x
h 1.5 0.6081976622 solve h x = 3.2 2.954165523 plot h x , x = 0 ..4 To get this we selected the f := a /y, from the Expression Palette, and then filled in for f, and for a. Positioning the cursor at y, we then selected the - x x !a x x Ra item from the palette. We edited what was there. Once defined, h is available for evaluation within expressions. The solve operation tries to find (numerically, using limited-precision arithmetic) a value of x such that h(x) is approximately equal to 3.23.2 is greater than 1.5, and 2.954165523*log (2.954165523) is approximately 3.2. (1.7.5) (1.7.5) (1.7.2) (1.7.2) (1.6.11) (1.6.11) (1.7.4) (1.7.4) (1.6.13) (1.6.13) (1.7.1) (1.7.1) (1.6.10) (1.6.10) (1.6.9) (1.6.9) (1.7.3) (1.7.3) (1.6.12) (1.6.12) (1.6.14) (1.6.14) x 1 2 3 4 0 1 2 3 4 5
Textual interface Commentary h2 d x / piecewise x !1.5, x, 1.5 % x, x $log x x/piecewise x !1.5, x, 1.5 %x, x log x solve h2 x = 3.3 3.001983443 h x Kh2 x 0 Maple formatted the as a right-arrow after we entered it. it also formatted a that we typed as as %. Calculations with piecewise expressions Many scientific and engineering situations can be modeled with piecewise expressions. Maple can apply solve, diff , and int on piecewise expressions, This can often save you time over trying to perform the operations on the pieces separately. Calculus on piecewise expressions and functions Example Commentary Problem: An ion-powered space probe is moving through a gaseous nebula. For the first ten hours the ion engine is on, and, it (1.7.1) (1.7.1) (1.7.5) (1.7.5) (1.7.2) (1.7.2) (1.7.3) (1.7.3) (1.7.4) (1.7.4) travels at a rate of .05$t 2 meters per second. Then the motor shuts off an the gas in the nebula gradually slows the space probe down. The velocity of the space probe can be described as:
0 t !0 5 100 $t 2 0 %t !10 5 100 $10 2 $exp Kt C10 t R10 What is the position of the space probe at t=20 hours? Solution velocity d 0 t !0 5 100 $t 2 0 %t !10 5 100 $10 2 $exp Kt C10 t R10 0 t !0 1 20 t 2 0 %t and t !10 5 e Kt C10 10 %t plot velocity, t = 0 ..20 We assign the piecewise expression to the variable velocity and plot it to better understand it. The plot reveals that there are not any discontinuities in velocity, although there is an abrupt transition at t=10. (1.7.5) (1.7.5) (1.7.2) (1.7.2) (1.7.9) (1.7.9) (1.7.8) (1.7.8) (1.7.7) (1.7.7) (1.7.4) (1.7.4) (1.7.1) (1.7.1) (1.7.3) (1.7.3) (1.7.6) (1.7.6) t 5 10 15 20 0 1 2 3 4 position d int velocity, t 0 t %0 1 60 t 3 t %10 K5 e Kt C10 C 65 3 10 !t eval position, t = 20.0 21.66643967 Since position is the integral of velocity, we can get an expression for the position by symbolically integrating velocity with respect to time. To find the position at t=20, we evaluate the expression position at that value. By giving the floating point number 20.0 instead of the exact number 20, we ensure that the result is given as a floating point number. distance d int velocity, t = 0 ..20.0 21.66643967 We should get the same result if we integrate velocity for t=0 to t=20 Piecewise integration Problem 4(c) Anton, problem 6.7.42. A sprinter in a 100 m race explodes out of the starting block with an acceleration of 4.0 m s 2 , which she sustains for 2.0s. Her acceleration then drops to zero for the rest of the race. (a) What is her time for the race? Make a graph of her distance from the starting block versus time. Solution Create a piecewise expression modeling the acceleration. aexpr d piecewise 0 %t and t %2, 4, 0 (1.7.9) (1.7.9) (1.7.8) (1.7.8) (1.7.7) (1.7.7) (1.7.6) (1.7.6) 4 0 %t and t %2 0 otherwise We integrate the acceleration expression to get a velocity expression. vexpr d int aexpr, t 0 t %0 4 t t %2 8 2 !t We integrate the velocity expression to get a position expression. dexpr d int vexpr, t 0 t %0 2 t 2 t %2 8 t K8 2 !t We use fsolve to find approximately the time when the runner reaches 100 meters. finishTime d fsolve dexpr = 100, t 13.50000000 We plot distance versus time to confirm the answer from fsolve. plot dexpr, t = 0 ..finishTime, labels = "time (in seconds)", "position (in meters)" (1.7.9) (1.7.9) (1.7.8) (1.7.8) (1.7.7) (1.7.7) (1.7.6) (1.7.6) time (in seconds) 0 2 4 6 8 10 12 position (in meters) 0 20 40 60 80 100 Piecewise integration, continued Problem Two racers are in the race. One accelerates at 2m/sec^2 for 4 seconds, as described previously. The other accelerates at 2.1 m/sec^2 for 3.8 seconds. Who gets to the finish line first? Solution Create a procedure that turns the previous script into something that can handle other accelerations. The procedure should take two parameters, the initial acceleration rate aInit, and the period of time tInit that this acceleration lasts. After the initial acceleration, the racer is assumed to run at the final velocity attained for the rest of the race. We want the procedure to return the time to complete the race. It should also, as a side-effect, print out the plot but it should not return the plot structure as a result. racer := proc( aInit, tInit) local aexpr, vexpr, dexpr, finishTime, plotStructure; #Define acceleration aexpr := piecewise(0 <= t and t <= aInit, tInit, 0); #Calculate velocity and distance travelled. vexpr := int(aexpr, t); dexpr := int(vexpr, t); #Calculate approximate time to finish. finishTime := fsolve(dexpr = 100, t); #print out postion vs. time. print(plot(dexpr, t = 0 .. finishTime, labels = ["time (in seconds)", "position (in meters)"])); #return finishing time. return finishTime; end proc: #Test the procedure on the original problem r1 :=racer(2.0, 4.0); time (in seconds) 0 2 4 6 8 10 12 position (in meters) 0 20 40 60 80 100 13.50000000 r1 :=racer(2.0, 4.0); r2 := racer(2.1, 3.8); #while the if statement is not really worthwhile if #we only wanted to compare two racers, we are considering #the possibility that we might want to do this #frequently and so write for easy reuse. if r1< r2 then print("Racer 1 won!"); elif r1>r2 then print("Racer 2 won!"); else print("They tied!"); end if; time (in seconds) 0 2 4 6 8 10 12 position (in meters) 0 20 40 60 80 100 13.50000000 (1.7.10) (1.7.10) time (in seconds) 0 2 4 6 8 10 12 position (in meters) 0 20 40 60 80 100 13.58132832 "Racer 1 won!" Because piecewise expressions are similar to if then .. end if, it is tempting to think that they are interchangable. One thing to keep in mind is that operations such as int evaluate all their arguments before they start to try to figure out their results. If one of the arguments involves a procedure, then the procedure needs to work with symbolic rather than numeric arguments. The difference between piecewise and a procedure with if then else. int abs b , b Error, (in int) integration range or variable must be specified in the second argument, got piecewise(x < 0, -x, 0 <= x, x) Integrating the absolute value function returns a piecewise expression. (1.7.10) (1.7.10) procAbs d proc x if x R0 then return x else return Kx end if; end proc x if 0 != x then return x else return Kx end if end proc int procAbs b , b Error, (in procAbs) cannot determine if this expression is true or false: 0 <= piecewise(x < 0, -x, 0 <= x, x) We write a Maple procedure to emulate the absolute value function...We find that Maple can't integrate it because it tries to get a formula for procAbs(b) and then integrate that. But the procedure can't run with b only a symbol. Curve fitting with splines In scientific and engineering work, we often start with numerical measurements of a phenomenon. but need ways of knowing something about the mathematical behavior of the phenomenon for values other than those measured -- to make predictions, or to do mathematical modeling operations such as equation-solving, integration, or optimization that require formulae. A typical way of handling this is to construct a model (a formula) from the data. Linear least squares data fitting, described in this section, is a way of doing this. However, it can only find formulas that are straight lines. . While there are techniques for non-linear least squares for certain kinds of models-- linear, quadratic, exponential, logarithmic, etc -- they all require that the modeler know ahead of time that whether the relationship should be linear, quadratic, or whatever. Picking the wrong kind of relationship may produce a procedure that doesn't very closely model the data. There is a different kind of formula-fitting called spline interpolation. The advantage of the data fitting using splines is that the modeler does not have to know ahead of time whether the relationship is linear, quadratic, etc. A spline interpolant builds a piecewise expression that is guaranteed to agree exactly at every data point, instead of hopefully being close by as with least squares fitting. (1.8.2) (1.8.2) (1.8.8) (1.8.8) (1.8.7) (1.8.7) (1.8.5) (1.8.5) (1.8.3) (1.8.3) (1.8.9) (1.8.9) (1.8.4) (1.8.4) (1.8.1) (1.8.1) (1.8.6) (1.8.6) Spline interpolants differ in the kind of function used for each piece of the expression. A linear spline connects the data points together with straight lines. That is, it is a piecewise expression where a linear expression describes each piece. A piece corresponds to the interval between two consecutive data points. A quadratic spline is a piecewise expression where each piece connects two consecutive data points together with a degree 2 polynomials. cSimilarly there are cubic splines, quartic splines, etc. Typically quadratic or cubic splines are used for data fitting since they produce smooth curves that can be computed quickly. Linear splines We enter a collection of data values dataValues d 1, 3 , 1.5, 2.8 , 2.1, 4.6 , 3.0, 4.4 dataValues d 1, 3 , 1.5, 2.8 , 2.1, 4.6 , 3.0, 4.4 ... and plot them. dataPlot d plot dataValues, style = point, view = 1 ..4, 0 ..5 , symbol = diamond, symbolsize = 20 , color = "Purple" dataPlot dPLOT ... print dataPlot (1.8.2) (1.8.2) (1.8.8) (1.8.8) (1.8.7) (1.8.7) (1.8.5) (1.8.5) (1.8.3) (1.8.3) (1.8.9) (1.8.9) (1.8.4) (1.8.4) (1.8.1) (1.8.1) (1.8.6) (1.8.6) 1 2 3 4 0 1 2 3 4 5 We load in the CurveFitting package, and construct a linear spline which we call s. Without the with, we could just do CurveFitting[Spline]. with CurveFitting ArrayInterpolation, BSpline, BSplineCurve, Interactive, LeastSquares, PolynomialInterpolation, RationalInterpolation, Spline, ThieleInterpolation s dSpline dataValues, t, degree = 1 s d 3.400000000 K0.4000000000 t t !1.5 K1.700000000 C3.000000000 t t !2.1 5.066666667 K0.2222222222 t otherwise We display a plot of the spline, with the data point plot. This shows that the spline s does agree with all the data points. (1.8.2) (1.8.2) (1.8.8) (1.8.8) (1.8.7) (1.8.7) (1.8.5) (1.8.5) (1.8.3) (1.8.3) (1.8.9) (1.8.9) (1.8.4) (1.8.4) (1.8.1) (1.8.1) (1.8.6) (1.8.6) plots display plot s, t = 0 ..4 , dataPlot t 0 1 2 3 4 0 1 2 3 4 5 To get a prediction of what to expect for say t=2.3, we just evaluate s at that point. eval s, t = 2.3 4.555555556 (2.3, 4.556) is on the line connecting the data points 2.1, 4.6 and 3.0, 4.4 . Maple's standard math operations know how to work with the piecewise expression that the spline generator produces. Optimization Maximize s, t = 1 ..3.1 4.59999999843952, t = 2.10000000873216 int s, t = 1 ..3.1 8.158888889 fsolve will find one solution, but if we want the solution to be inside the range of values that we measured, we should specify the interval fsolve s = 3.1 (1.8.13) (1.8.13) (1.8.15) (1.8.15) (1.8.8) (1.8.8) (1.8.5) (1.8.5) (1.8.3) (1.8.3) (1.8.4) (1.8.4) (1.8.6) (1.8.6) (1.8.2) (1.8.2) (1.8.12) (1.8.12) (1.8.7) (1.8.7) (1.8.9) (1.8.9) (1.8.1) (1.8.1) (1.8.11) (1.8.11) (1.8.14) (1.8.14) 0.7500000000 fsolve s = 3.1, t = 1 ..4 1.600000000 One problem with linear splines is that they can have sharp corners, as demonstrated by the example just given. It is possible, with sufficient data points, to construct splines where the pieces are quadratic, cubic, or of even higher degree. This has the advantage that the bends in the spline will be smoother. How smooth depends on the degree. However, higher degree splines may do undesirable things for values outside the ranges being measured. For that reason, it's better to use splines for problems where you need results for values inside the ranges being measured. Quadratic splines and splines of higher degrees The alternative form of spline construct takes two lists, one for first coordinate, and one for the second. tValues d 1, 1.7, 2.1, 3.7, 4.1 tValues d 1, 1.7, 2.1, 3.7, 4.1 mValues d 3, 2.7, 4.8, 4.4, 3.1 mValues d 3, 2.7, 4.8, 4.4, 3.1 We can plot them. dataPlot2 d plot tValues, mValues, style = point, view = 1 ..8, 0 ..8 , symbol = diamond, symbolsize = 20 , color = "Purple" dataPlot2 dPLOT ... print dataPlot2 (1.8.13) (1.8.13) (1.8.15) (1.8.15) (1.8.12) (1.8.12) (1.8.11) (1.8.11) (1.8.14) (1.8.14) 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 With load in the CurveFitting package, and construct a quadratic spline which we call s2. Without the with, we could just do CurveFitting[Spline]. with CurveFitting ArrayInterpolation, BSpline, BSplineCurve, Interactive, LeastSquares, PolynomialInterpolation, RationalInterpolation, Spline, ThieleInterpolation s2 dSpline tValues, mValues, t, degree = 2 s2 d 3.00000000000000 C7.93016446160826 10 K16 t K3.50975329890993 t K1 2 t !1.35000000000000 K2.73892713711991 C3.19936890418818 t C8.08028030489304 t K1.7 2 t !1.90000000000000 K5.56910499139415 C4.93766904352102 t K3.73452995656094 K2.1 Ct 2 t !2.90000000000000 18.6912916974019 K3.86251126956807 t K1.76558273911974 t K3.7 2 t !3.90000000000000 3.10000000000000 C11.4218609130399 t K4.1 2 otherwise (1.8.13) (1.8.13) (1.8.15) (1.8.15) (1.8.12) (1.8.12) (1.8.11) (1.8.11) (1.8.14) (1.8.14) We display a plot of the spline, with the data point plot. This shows that the spline s does agree with all the data points. plots display plot s2, t = 0 ..5 , dataPlot2 t 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 To get a prediction of what to expect for say t=2.3, we just evaluate s at that point. eval s, t = 2.3 4.555555556 The formula does have the drawback that it starts increasing after t=4.1, even though the data doesn't. This is a property of higher degree polynomials. We might not want to use this model if we need to extrapolate very far beyond the values that were measured. Higher degree spline interpolation produces piecewise expressions that all agree fairly closely for values within the t values measured within the region defined by the data points. However, they may differ significantly outside the region of the data points. s1 d Spline tValues, mValues, t, degree = 1 : s3 d Spline tValues, mValues, t, degree = 3 : s4 d Spline tValues, mValues, t, degree = 4 : (1.8.13) (1.8.13) (1.8.15) (1.8.15) (1.8.12) (1.8.12) (1.8.11) (1.8.11) (1.8.14) (1.8.14) plots display plot s1, t = 0 ..5, color = black , plot s2, t = 0 ..5, color = red , plot s3, t = 0 ..5, color = green , plot s4, t = 0 ..5, color = blue , dataPlot2 t 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 Chapter summary Indefinite integration with int The clickable interface can be used to input an indefinite integration problem for Maple to compute. Use the f dx item in the Expression Palette, then edit the expression f and the variable (1.9.5) (1.9.5) (1.9.2) (1.9.2) (1.9.3) (1.9.3) (1.9.4) (1.9.4) (1.9.1) (1.9.1) of integration x to suit your problem. The general form of the textual version of the command is int( expression , var ) This computes the anti-derivative of the expression, with respect to the variable var. If the answer is just a formula involving expressions that the user already knows about (e.g. ones that involve numbers, polynomials, rational functions, trig, logarithm and exponential functions), when Maple can find one, is sometimes referred to as a closed form solution to the integration problem. Indefinite integration with int Example! Commentary 1 x dx ln x cos x 2 dx 1 2 cos x sin x C 1 2 x cos 2 x dx 1 2 cos x sin x C 1 2 x The clickable interface can be used to enter the integration problem. Note that in the clickable interface there are two ways of entering what is "cos x $cos x ". int sqrt x , x 2 3 x 3 / 2 int cos a $sin a 2 , a K 1 3 cos 3 2 a Ccos 1 2 a The textual form of integration works in the same way. This is use of the textual form of the command in a small script. The script computes the symbolic integral and stores it in i1. Then it takes the derivative of i1 and assigns that to d1. (1.9.11) (1.9.11) (1.9.6) (1.9.6) (1.9.2) (1.9.2) (1.9.10) (1.9.10) (1.9.4) (1.9.4) (1.9.7) (1.9.7) (1.9.1) (1.9.1) (1.9.9) (1.9.9) (1.9.12) (1.9.12) (1.9.5) (1.9.5) (1.9.8) (1.9.8) (1.9.3) (1.9.3) expr := tan(t) + x^2; i1 := int(expr,t); d1 := diff(i1,t); difference := d1-expr; print("difference:". difference); print("simplified difference:", simplify(difference)); tan t Cx 2 Kln cos t Cx 2 t sin t cos t Cx 2 sin t cos t Ktan t "difference:". sin t cos t Ktan t "simplified difference:", 0 According to the Fundamental Theorem of Calculus, d1 should be the same as expr. However, we have to get Maple to simplify the difference in order to have it actually be reduced to zero. Definite Integration examples Example Commentary Anton, Calculus 8th ed. problem 6..5.14. Calculate K10 5 6 dt , K p 3 p 3 sin x dx, 0 3 x K2 dx , 0 2 4 Kx 2 dx . K10 5 6 dt Using the clickable interface. (1.9.11) (1.9.11) (1.9.6) (1.9.6) (1.9.10) (1.9.10) (1.9.7) (1.9.7) (1.9.9) (1.9.9) (1.9.12) (1.9.12) (1.9.8) (1.9.8) 90 int sin x , x =K p 3 .. p 3 0 0 3 x K2 dx 5 2 int(sqrt(4-x^2),x=0..2); p Using the document interface but with the textual form of the operation. Using the clickable interface again. Entry of the operation within a code edit region. Anton problem 6.6.25. Calculate 1 4 3 t K5 t Kt K 3 2 dt int 3 / sqrt t K5 * sqrt t Kt^ K3 / 2 , t = 1 ..4 K 55 3 Anton problem 32 (a). Calculate K3 3 x 2 K1 K 15 x 2 C1 dx . Answer should be 30* arctan(13/9) + 28/3. int abs x^2 K1 K15 / x^2 C1 , x =K3 ..3 28 3 K30 arctan 3 C60 arctan 2 simplify (1.9.10) 30 arctan 13 9 C 28 3 The original form of the answer given by Maple does not match the answer key, but fortunately the simplify function reduces the result to the desired form. This does not always happen for definite integration results. Sometimes further manual operation may be necessary. Maple can do improper definite integrals since it can do symbolic limits (1.9.17) (1.9.17) (1.9.11) (1.9.11) (1.9.6) (1.9.6) (1.9.10) (1.9.10) (1.9.7) (1.9.7) (1.9.9) (1.9.9) (1.9.16) (1.9.16) (1.9.14) (1.9.14) (1.9.18) (1.9.18) (1.9.12) (1.9.12) (1.9.15) (1.9.15) (1.9.8) (1.9.8) (1.9.19) (1.9.19) (1.9.13) (1.9.13) Anton Example 4, ch. 8 Evaluate KN N 1 1 Cx 2 dx KN N 1 1 Cx 2 dx p Anton Example 6 (c) Ch 8. Evaluate 0 N 1 x $ x C1 dx answer := int(1/(sqrt(x)*(x+1)), x = 0 .. infinity); printf("sin evaluated at the answer is: %a", sin(answer)); p sin evaluated at the answer is: 0 (e.g. the functionality available through limit). You can input infinity by through the "Common Symbols" palette that can be found on the left hand side of the Maple application window. Infinity is can also be input textually as the symbol . Approximate definite integration examples int exp x 2 log x 2 , x = 2 ..3 2 3 e x 2 ln x 2 dx evalf (1.9.13) 694.1492846 int exp x 2 log x 2 , x = 2 ..3.0 694.1492846 int exp x 2 log x 2 , x = 1 ..3 Maple is unable to calculate the exact solution to this definite integration problem. evalf says that the area is approximately 694.15. Note that the difference between this and the original input was that we have changed the upper limit of integration from "3" to "3.0". Because this is a floating point number, Maple will use evalf automatically. (1.9.16) (1.9.16) (1.9.14) (1.9.14) (1.9.18) (1.9.18) (1.9.17) (1.9.17) (1.9.15) (1.9.15) (1.9.19) (1.9.19) (1.9.13) (1.9.13) 1 3 e x 2 ln x 2 dx evalf (1.9.16) Float N This is the same integrand. Note that the lower limit of integration is where the integrand is infinite. Not surprisingly, the approximation method doesn't give us a number for the answer. Since the approximation method doesn't guarantee that its answer is close to the actual answer, this result doesn't prove that the area under the curve is infinite. Further analysis by a mathematician might establish this conclusively. int x 6 C2$x C1 x 3 C2$x 2 C1 , x = 0 ..1 K > _R= RootOf _Z 3 C2 _Z 2 C1 1 _R 3 _RC4 2 5 K_R C10 _R 2 ln K_R K 89 12 C > _R= RootOf _Z 3 C2 _Z 2 C1 1 _R 3 _RC4 2 5 K_R C10 _R 2 ln 1 K_R int x 6 C2$x C1 x 3 C2$x 2 C1 , x = 0 ..1.0 1.161103706 There is a symbolic solution to the integral, but it's messy. An explanation of "RootOf" can be found in Example 17.1.3.2. As with the integrand above, making the upper limit of integration into a floating point number invokes the approximation technique that evalf uses. Calculating arclength Student[Calculus1][Arclength]([ x expression, y expression], parameter = a..b) calculates the arclength of a curve described by the parametric expressions in the two coordinates. The package uses the definite integration feature of Maple. Therefore, it will use approximate methods if a, b, or any number in the expressions is a floating point number. (1.9.21) (1.9.21) (1.9.23) (1.9.23) (1.9.20) (1.9.20) (1.9.22) (1.9.22) Student[Calculus1][Arclength](f(x), x = a..b); calculates the arc of the curve given by the parameterization x=t, y=f(t) Student[Calculus1][Arclength](f(x), x = a..b, showfunction=true); calculates the arc of the curve given by the parameterization x=t, y=f(t) Student[Calculus1][Arclength]([ x expression, y expression], parameter = a..b, output=plot, showfunction=true, showintegral=true, showintegrand=true); Piecewise expressions A piecewise expression uses different expressions to describe the value for different ranges of the controlling variable. It can be entered either with the clickable interface or textually. To add more branches to a piecewise expression. In the clickable version, you can add an extra row by typing control-shift-R (on Macintosh, command-shift-R) in the bottom row. In the textual version, you can add extra items onto the sequence of inputs to the function. If the word otherwise is used for a range in the clickable interface, then the expression associated with that branch will be used for all other values of the controlling variable. The otherwise branch is specified in the textual version of piecewise as the odd last argument to piecewise . A difference between piecewise expressions and if then ... end if is that Maple can do mathematical operations such as +, solve, diff, int, or plot on piecewise expressions, while it can't do so as easily with if then ... end if. h dx/ x x !1.5 x$log x x R1.5 x/piecewise x !1.5, x, 1.5 %x, x log x
h 1.5 0.6081976622 solve h x = 3.2 2.954165523 step3 d piecewise K2$p %x %p, sin x , p !x !5, 0,K2 (1.9.21) (1.9.21) (1.9.22) (1.9.22) (1.9.23) (1.9.23) (1.9.20) (1.9.20) sin x K2 p %x and x %p 0 p !x and x !5 K2 otherwise plot step3, x =K10 ..10 x K10 K5 0 5 10 K2 K1 1 351 lndex Symbols ! (exclaimation point Iactorial), 12 ! icon (execute group), 188 !!! (execute worksheet), 66 " (double-quote), 77 # (program comment), 189 ' (apostrophe), 84 (, 11 ), 11 - (minus or dash), 11 -inIinity, 325, 331 : (colon), 188 :, 45 ; (semi-colon), 188 (equation), 23 ` (caret), 12 (underscore), 45 ` (backquote), 84 a symbolic constant, 29, 33, 34 , 111 A abs (absolute value), 107 accumulation loop, 289 actual parameter, 77 acute accent marks (`), 84 addition (), 10 alpha (Greek letter), 321 altitude, 174 and (Boolean operation), 217, 237 animate (plots package), 158, 180 animation controls, 159 animations exporting to GIF Iormat, 183 apostrophe, 132 apostrophes, 84 approximation Iloating point, 228 arccos (inverse oI cosine), 29 arcsin (inverse oI sine), 29, 107 arctan (inverse oI tangent), 29 arguments oI Iunction, 77, 105 arithmetic, 10 approximate, 29 exact, 13 operations, 10 arrow, 111 arrow key right, 13 assignment, 24 mental model oI, 48 multiple, 285 oI a plot structure to a variable, 147 undoing, 49 assistant Unit Converter, 136 asterisk, 11 autosaving, 22 average oI numbers in a list, 93 Axiom, 4 B backquotes, 84 backspace key, 17 backups retrieving, 22, 22 ball, 174 base oI natural logarithm (e), 33 blue, 151 Boole George (1815-1864), 213, 215, 217, 236, 237 Boolean values, 202 brackets, 62 by, 245, 247, 247, 247, 247, 247, 260, 261, 261, 261, 261 C C (programming language), 4, 6, 55 C (programming language), 5 Canadian, 92 Canadian roots, 152 Canvas (Maple word processor Ieature), 43 caret (power), 12 circle, 152, 156, 176 Iunction, 152 circle-X, 7 clickable interIace, 80 code edit region, 187 Code Edit Region collapse, 192 execute, 192 resize, 190 code icon clicking on, 192 Collapse Code Edit Region, 192 colon, 188, 195, 269 Colorado, 63 colornames (plot), 167 352 Index colors plotting, 91 comma, 62 command-, 41 command-C (copy operation), 17, 66 command-e (execute region), 188 command-R, 42 switch to math mode, 40 command-T switch to text entry mode, 40 command-V (paste operation), 17, 66 command-X (cut operation), 17 comment program (#), 189 Commenting out printing statements, 268 comments header, 189 completion command, 109 Component Properties, 190 composition oI Iunctions, 125, 128, 128 computing algebraic, 1 graphical, 1 high perIormance, 2 logical, 1 numerical, 1 constant symbolic, 57 control-, 41, 42, 320 control-C (copy operation), 17, 66 control-click, 23 control-e (execute region), 188 control-R, 42 switch to math mode, 40 control-T, 42 switch to text entry mode, 40 control-V (paste operation), 17, 66 control-X (cut operation), 17 convert, 174, 174, 282 a list into a sequence, 93 a list into a string, 93 between units, 121, 131 converting table into list, 282 copy (editing operation), 17 copy and paste, 66 crash Maple, 22 curly braces, 62 currency, 130 current state oI a Maple session, 48 cut (editing operation), 17 D daisy chaining, 125 Iunctions, 128 dashed rectangle, 8 days, 132 degrees, 121 delimiters in Maple: ( ) | | } , 15 derivative, 320 diII, 319, 322, 344 diIIerentiate right-click menu item, 328 diIIerentiate menu item, 320 diIIerentiation, 319 oI expression palette, 320 digits, 30 disk (plottools Iunction), 167 display, 149, 179 Iunction, 149, 152 divide and conquer, 68 division (/), 11 documentation need Ior, 2 dot centered, 13 double-quotes, 84 E e Irom keyboard not a symbolic constant, 33 natural logarithm and symbolic constant, 29, 33, 34, 42 Edit-~Execute-~Selection, 66 Edit~Execute~Worksheet., 66 ellipse, 156 ENGR101, 68 enter, 41, 49, 66 entries, 281, 285 equation, 23, 61, 279 error attempting to assign to Pi which is protected, 57 attempting to assign to `solve` which is protected , 57 controlling variable oI Ior loop must be a name, 57 illegal use oI an object as a name, 56 invalid Iraction, 16 invalid leIt hand side in assignment, 283 invalid matrix/vector product, 14 invalid operator parameter name, 116 invalid power, 78 invalid sequence, 15 invalid sum/diIIerence, 14 logic, 20 missing operation, 14 Index 353 numeric exception: division by zero, 14 semantic, 19 unable to match delimiters, 15, 15, 78 unexpected option, 84 vocabulary, 19 Error (in IprintI) integer expected Ior integer Iormat, 265, 268 (in IprintI) number expected Ior Iloating point Iormat, 264 ambiguous multiple assignment, 286 missing operator or `;`, 257 reserved word `do` unexpected, 258 unexpected `local` declaration, 232 error message, 13 escape key (ESC), 42, 109 Euro, 128 eval, 120, 319 evalI, 121 evaluating preventing, 132 state, 22 evaluation, 46 at a point, 66 oI a Iormula, 155 oI a Iunction, 77 oI expressions, 10 evaluation oI a derivative expression, 319 execute region, 188 execution trace, 269, 272 exp (exponential Iunction), 108 exponentiation, 18 Exporting animations, 183 expression, 279 expressions algebraic, 23 Irom palette, 28 extrema , 325 F Iactorial (!), 12 Ialse (Boolean operation), 213, 214, 214, 216, 237 Ialse (Boolean value), 202 Ience post error, 32 Iind something similar, 68 Format -~ Create Document Block, 43 Formatting output as currency, 130 Fortran, 4 Ireeze Irame animation, 159 Iruit Ilies, 111 Isolve, 119, 279 It, 131 Iunction Boolean, 213, 214, 217, 237 idea oI, 105 Iunction deIinition, 116 Iunction deIinition alternative, 117 Iunction evaluation, 77 Iunctions deIine, 111 designing Irom word problems, 125 thousands oI built-in, 108 Iuzzy notions, 67 G gallons, 121, 132 Imperial, 92 gigaIlop, 3 graphical user interIace (GUI), 4 Graphics Exchange Format (GIF), 183 Greek letters, 321 green, 151 H header comments, 189 help on-line, 88, 101, 109 table oI contents Ior, 196 quick, 7 through command completion, 109 using on-line, 110 Help (Maple menu), 43 horsepower, 131 hour, 121, 121, 131 hypotenuse, 140 l I (square root oI -1), 57, 63 Ideal Gas Law, 125 Image (Maple word processor Ieature), 43 immutable, 279 inch, 121, 131 index, 61, 152, 280 indices, 281, 284 inequalities, 61 inIin (shortcut Ior inIinity in math mode), 42 inIinite loop, 235 inIinity, 324, 325, 331 Insert (Maple menu item), 43 Insert-~2-D Math, 40 Insert-~Code Edit, 187 Insert-~Text, 40 interactive, 5 inverse trig Iunctions, 29 354 Index isprime, 246, 262 ] Java, 4, 5, 55 K Kessel Run, 132 key, 280 kilometer, 131, 133 kilopascals, 126 kilowatt, 131 L label, 10 labels Ior axes plotting, 91 lady little old, 289 LeastSquares, 117 leIt arrow key, 17 leIt hand side, 61 leIt hand side (right-click menu), 31, 35 lhs, 120, 279 limit leIt sided, 325 one sided, 325 right sided, 325 line Iunction, 151, 152 linear algebra, 14 list, 62, 81, 279 add together items Irom, 93 count number oI items in, 93 empty, 279 one item Irom, 93 operations on, 92 part oI, 93 liters, 121 log10 (base 10 logarithm), 107 logarithm base e, 29 logic error, 20, 32 loop accumulation, 289 inIinite, 235 suppressing output Irom, 269 Los Alamos National Laboratory, 3 M Macsyma, 4 Maple, 4, 4 as a word processor, 39 document mode, 7 math entry mode, 39 Mathematica, 4, 6 mathematical model, 1 mathematical models, 154 Matlab, 4, 55 Symbolic Toolkit, 6 max (maximum oI arguments), 107, 118 maxdigits, 19 maximize, 331, 335 meter, 121, 131 micrometer, 131 mile, 131 millimeter, 131 min (minimum oI arguments), 107, 118 minimize, 331, 334, 340, 345 minus, 11 minute, 132 mistake typographical how to Iix, 17 mod, 262 multiple assignment, 285 multiple systems, 6 multiplication (*), 11 multivariate, 344 MuPad, 4, 55 N name assignment to, 45 National Forest Service, 65 negation (-), 11 negative inIinity, 325 nops, 279, 280 not (Boolean operation), 213, 215, 217, 237 NULL, 331 O Oak Ridge National Laboratory, 3 objective Iunction, 325 Octave, 4 old really really, 293 omega (Greek letter), 42 Omega (upper case Greek letter), 42 on-line documentation, 87 op, 279 operation Boolean (and or, not), 213, 214, 217, 237 Index 355 Optimization, 339 Optimization|Maximize|, 337 Optimization|Minimize|, 337, 345 options plot, 120 or (Boolean operation), 213, 215, 217, 237 orange, 151 oscilloscope, 68 P packages library, 117 palette, 28 Expression, 80, 105, 111, 111, 118, 320 square root, 28 Palette Greek, 321 palettes, 42 parameter, 66 parameterized plots, 156 parentheses, 11, 77 parsec, 132 paste (editing operation), 17 petaIlop, 3 Pi, 57 Pi (symbolic constant), 57 pick names, 67 pitIalls common in Maple, 105 playing animation, 159 plot, 119, 279 a Iormula, 25 builder, 87 colors, 84 Ior insight into a mathematical relationship, 155 labels, 84 options, 91 structure, 147 symbol Ior point plot, 176 symbol size Ior point plotting, 176 plot options, 120 Plot structures, 280 plot3d, 345 PlotBuilder, 26 plots package, 150 plottools, 151 plus, 10 pop-up, 117 power (`), 12 pressure, 137 preventing evaluation, 132 print, 195 procedure with a numerical result, 227 procedures returning multiple results, 287 Python, 6
Quick ReIerence (help menu item), 43
quotation, 132, 132 R radians, 121 range, 279 ready (status oI Maple), 22 rectangle dashed (entry), 8 red, 151 reIactor code, 129 replay animation, 160 restart, 57, 57, 68, 272 reuse oI soItware, 2 rhs, 120, 279 right arrow key, 13 right hand side, 61 right hand side (oI equation), 30 right hand side (right-click menu), 31, 35 right-click, 23, 320 optimization menu item, 337 S SAGE, 4 scalingconstrained (option to plot), 156 scripting, 63 search Iield Ior help, 88 select entry, 61 item Irom a set, 30 select entry (right-click menu), 31, 35 semantic error, 19 semi-colon, 188 sequence, 15, 62, 140, 280, 285, 287 empty, 280 set, 62, 280 empty, 74, 280 sheep, 63 356 Index shortcuts keyboard, 42 Show Al Palettes, 42 simpliIy, 320, 321 simpliIy -~ assuming real (clickable operation), 108 simpliIy(.... trig) , 321 simulation, 1 single-quotes, 84 slash, 11 small steps, 67 Solo Han, 132 solve, 61, 77, 101, 119, 279 a system oI equations, 93 by right-clicking or control-clicking, 24 numerical, 30 won't work with an assigned variable, 57 solving an equation, 155 speed animation, 160 sqrt (square root), 107 square root Irom palette, 28 Star Wars, 132 state current oI a Maple session, 49 current oI Maple session, 48 state display oI Maple, 22 statement program, 188 stop playing animation, 159 sublist, 93 subscript, 41 subtraction (-), 11 sum, 256 supercomputer, 2 suppress output, 195 suppressing output Irom a loop, 269 symbol Ior point plotting, 176 symbolsize, 176, 176 T table, 280 in an accumulative loop, 289 Table (Maple word processor Ieature), 43 temperature, 137 template textual, 109 teraIlop, 3 test, 68 testing, 126 a program, 117, 117 Iunctions, 127 text entry mode, 40 text mode to math mode can't switch back, 43 textual entry, 77 to (part oI Ior), 245 Tools-~Spellcheck, 43 trace, 272 triangle, 140 troubleshooting, 67 assignment, 55 Iunction deIinitions, 116 tables, 283 textual input, 101 unit conversion, 132 word processing, 43 true (Boolean value), 202, 213, 216, 237 truth values, 202 ttrace execution, 269 U unassign, 47, 47, 49, 57 undeIined, 324 underscore, 41 underscore (), 45 Unit Converter assistant, 136 units, 174 Units Calculator, 92 untrace, 272 V value oI an unassigned name, 46 values Boolean, 213, 214, 217, 237 variable programming, 45 variable oI diIIerentiation, 320 vertical range, 80 View (Maple menu), 42 Visual Basic, 24 visualization, 1, 1 W Warning computation interrupted, 236 premature end oI input, 258 variable is implicitly declared local, 228, 233 Index 357 what you see is what you get, 39 WYSIWYG, 39 Y yard, 132, 132 358 Index
Analytics at Work Smarter Decisions Better Results by Thomas t Morison Thomas H. Davenport;Jeanne G. Harris;Robert Morison all chapter instant download
The Romance of Mathematics
Being the Original Researches of a Lady Professor of Girtham College in Polemical Science, with some Account of the Social Properties of a Conic; Equations to Brain Waves; Social Forces; and the Laws of Political Motion.
Analytics at Work Smarter Decisions Better Results by Thomas t Morison Thomas H. Davenport;Jeanne G. Harris;Robert Morison all chapter instant download
The Romance of Mathematics
Being the Original Researches of a Lady Professor of Girtham College in Polemical Science, with some Account of the Social Properties of a Conic; Equations to Brain Waves; Social Forces; and the Laws of Political Motion.