




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An example of maple programming, focusing on the computation of sums and logarithms using while loops. The code demonstrates how to initialize variables, set up loops, and add terms to a sum until a specified tolerance is met. The document also discusses the importance of proper indentation and commenting for program readability.
Typology: Assignments
1 / 28
This page cannot be seen from the preview
Don't miss anything!





















We have seen that even some of the easiest technical calculations break down into a series of operations, chained together. Realizing that we will typically need the computer to perform a "series of operations" is the motivation for making the transition to programming, where execution of many operations in a block is typical.
The Maple document interface that we have been using so far easily supports calculations where the user prompts to computer to do a series of steps by positioning the cursor at the first 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 often easier to work with when you have a few dozen instructions and will want to execute them all in a chain.
One can open a text field in the Maple document where one can enter a series of instructions. To do this, position your cursor where you want the text field to appear in the document, and with the mouse perform Insert->Code Edit Region
Figure 11.1.1 Insert->Code Edit Region menu
Once the field has been created, you can type the textual version of the Maple instructions you want executed. Each instruction (commonly referred to as a statement) must be separated by either a semi-colon, or a colon. If the statement ends in a semi-colon, then its value will be printed during execution of the region. If the statement ends in a colon, then printing of its value will be suppressed just as it is in operation of 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 Region (on Macintosh, control-click->Execute Region). The results will appear below the region in blue.
Figure 11.1.1 A code edit region with actions entered, separated by semi-colons.
Code region Commentary
Segments of lines that begin with # are regarded as program comments (for the program reader's eyes), not operations for Maple to carry out.
The "Collapse Code Edit Region" menu item of the clickable menu will reduce the entire window to an icon. If the first line of the region is a program comment, it will be listed to the right of the icon. Double clicking on the icon will execute the code within.
Figure 11.1.3 A collapsed code edit region
Code region Commentary
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 first line becomes displayed next to the code edit icon.
Saving your document frequently is a guard against developing a code region but then losing what you typed due to a program crash or other aberrant behavior.
When you execute the code region, previous assignments and definitions you have done in the worksheet still apply unless you explicitly have undone them with a restart; or a new assignment within the code region itself. Thus, if you did x := 47; in a previous code region window, then x's value will still be 47 when you execute a new code region (or execute the same region again) unless you have changed x since then.
a := sin(3.5 + cos( Pi/2) ;
Error, ; unexpected
a := sin( 3. 5 + cos( Pi/ 2 )
Warning, premature end of
input, use +
to avoid this message.
There's both a missing closing parentheses and a missing semi-colon here.
This is only a warning, and executing this region does perform the computation.
a := sin( 3. 5 )
Warning, inserted missing semicolon at end of statement K0.
a := sin(3.5) b := cos( 3. 5 )
Error, missing operator or ;
However, if 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.
Everything in the code edit region is just characters. There is no built-in automatic reformatting. No actions other than what you type at the keyboard or copy/paste with the mouse will occur other than "Execute Region". There is no way to specify that only part of a code region is to be done in execution. Output appears outside of the code region into the worksheet below.
3.3. The line with the while contains a continuation condition. Whenever the computer is going to execute the series of statements within the "while... end do", it figures out whether the continuation condition is true. If so, it does the series of statements. If not, it decides that the repetition is finished and moves onto the next instruction after the end do.
Like the conditions in piecewise expressions and piecewise functions described in Table 5.4.1 and Example 5.7.1, continuation conditions can contain inequalities or equalities, along with the logical modifiers and , or , and not.
Example 11.2.1 below uses the mathematical fact that for values of x close to 0,
sin(x) = x K
x^3 C
x^5 K
x^7 C
x^9 C ...
The program computes and adds together the first few terms of this sum, until the next term is less than a specified "small number" tol.
Example 11.2.1.1 Commentary
The initial instructions in the sequence set up the variables i , the value of x that we want to use (.3), the value of the first term of the sum, the initial value of the variable that will contain the sum, and the value of the small number. The instructions to be repeated are indented and are found within the while...do... end do. The sequence of four instructions is repeated until the magnitude of term is found to be less than the small number. This check occurs just before the instructions are done for the first time, and then each time after the four instructions are performed.
At the very end we print out a message that compares the value of the sum, with Maple's notion of what sin(.3) is.
Value of i
#Example 11.2.
i := 1;
evalpt := .3;
term := (evalpt^i)/i!;
print("term is", term);
s := term; #sum so far
tol := 10e-7;
#add on successive terms
while abs(term)>=tol do
i := i+2; term := (-1)^((i-1)/2)
*(evalpt^i)/i!;
print("term is", term)
;
s := s+term;
end do;
print("sum is: ",s, "compared
to:", sin(evalpt));
"term is", 0.
3 K0. "term is", K0.
5
"term is", 0.
7 K4.339285714 10- "term is", K4.339285714 10-
Value of evalpt Value of term (first time) Side effect of print Value of s (first time) Value tol , the small number
Next value of i (first time repetition) Next value of term Side effect of print statement within while. Next value of s.
Value of i (second time repetition) Value of term (second time) Side effect of print. Value of s (second time)
Value of i (third time repetition)
Next value of term (third time) print
Next value of s (third time)
#Race to the finish line, 11.2.
#initialize track and graphics parameters
with(plottools);
with(plots); #load in plotting packages
rad := .5; #parameter for drawing size
trackLength := 100; #length of a line, in units.
maxMove := 6; #maximum size of a random number
frameNumber := 0;
#set up vectors for the x and y position of the spot at the far left o
positionX := 0;
positionY := 0;
frame := table(); #Table to store frames of a movie.
move := rand(1..maxMove); #Can emit random integers between 1 and maxM
#Draw a line from (0,0) to (trackLength,0). This will be the track.
xLine:= line([0,0],[trackLength,0]);
#Draw the player at the position as a solid disk
player := disk([positionX,positionY], rad, color=red);
#Store the picture in a position in the table.
frameNumber := frameNumber+1;
frame[frameNumber] := display( [xLine,player],axes=none,scaling=constr
#Repeatedly, generate a move and draw a new picture.
#Stop repeating when the position moves beyond the end of the track.
while positionX<=trackLength do
m := move(); #Figure out a move, chosen at random. positionX := positionX + m; #Move that player by that amount
#Draw the player at the new position as a solid disk player := disk([positionX,positionY], rad, color=red);
#Store the picture in a position in the table. frameNumber := frameNumber+1; frame[frameNumber] := display( [xLine,player],axes=none,scal
end do:
#Show an animation of all the frames.
This example is similar to that of section 11.2.1. It computes successive terms of a sum for the natural logarithm:
ln x = x K 1 K
x K 1 2 C
x K 1 3 K
x K 1 4 C
x K 1 5 C ...
The output is more refined than the initial example, through the use of semi-colons and formatted printing ( printf ). We might prefer to use printf instead of print results if we were going to show the output of the execution to others, or if the formatting made it much easier for us to comprehend the execution trace.
Many experienced programmers put in informative printing statements into the scripts they develop. They realize that spending a bit of time presenting key information in a more organized, intelligible fashion will save them a lot of time when they are trying to find errors in their programming by looking at execution traces.
term is -1.797570e-03, sum is -1. term is -1.153441e-03, sum is -1. term is -7.453001e-04, sum is -1. term is -4.844451e-04, sum is -1. term is -3.165041e-04, sum is -1. term is -2.077058e-04, sum is -1. term is -1.368415e-04, sum is -1. term is -9.046742e-05, sum is -1. term is -5.999419e-05, sum is -1. term is -3.989613e-05, sum is -1. term is -2.659742e-05, sum is -1. term is -1.777191e-05, sum is -1. term is -1.189946e-05, sum is -1. term is -7.982551e-06, sum is -1. term is -5.364274e-06, sum is -1. term is -3.610569e-06, sum is -1. term is -2.433791e-06, sum is -1. term is -1.642809e-06, sum is -1. term is -1.110312e-06, sum is -1. term is -7.513113e-07, sum is -1. "sum is: ", K1.203971215, "compared to:", K1. 30, "terms used"
Section 11.3 Developing a script with while s
Much time can be saved in comprehending or remembering what a program does by "at a glance" indentation that indicates what is being repeated in a while. Typically the statements that are being repeated are indented more than the enclosing while. Example 11.2.1 shows appropriate indentation for a while.
The list of all the results being computed in a script is called the execution trace or just trace. While it is a good idea to see the entire trace initially, at some point the quantity of output induced by the repetitions will work against understanding. If you end a line in a script with a colon, it suppresses output of the result. If you end a while do ... end do with a colon, all the output from the repetitions within will be suppressed, even if none of the statements inside end with a colon.
Example 11.3.2.1 Commentary
#Example 11.3.2.
i := 1; evalpt := .3; term := (evalpt^i)/i!; print("term is", term); s := term; #sum so far tol := 10e-7;
#add on successive terms while abs(term)>=tol do i := i+2; term := (-1)^((i-1)/2)* (evalpt^i)/i!; print("term is", term); s := s+term; end do:
print("sum is: ",s, "compared to:", sin(evalpt));
"term is", 0.
"term is", K0. "term is", 0. "term is", K4.339285714 10- "sum is: ", 0.2955202066, "compared to:", 0.
The only difference between the program of Example 11.2.1 and this one is that the while statement ends with a colon (after the "end do"). The initial part of the trace is the same, but the part from the repetition contains only the output of the print operations inside the repetition.
Value of i Value of evalpt Value of term (first time) Side effect of print Value of s (first time) Value tol , the small number
Result of print (first repetition) Result of print (second repetition) Result of print (third repetition)
The message at the end.
When developing a script using the ordinary Document interface, you can use the execution trace to determine whether the sequence of actions is working according to your plans. There are two common problems with this:
There is so much output that it becomes hard to find the information you're looking for, or it takes too long for Maple to print out the execution trace. The repetition never stops, even though you thought it would.
For problem (1), there are three suggested tactics:
a) Check first that the portion of the script that occurs before the repetition (before the while ) is working. Develop the code in small segments, and test each one as you enter it. For example, if you envision creating a script of 15 lines, you can enter the first three, and execute the script as you have it so far. Verify that it does everything as you intend. Then add the next three lines, and test again. In this way There's no point in puzzling over a repetition's output if the lead-up hasn't worked. In other words, develop a script incrementally. b) As you become certain that sections of code work, then, you can replace the semi-colons with colons, to suppress printing of results in that section. In addition, you can put in print or printf statements that will always print out information even if you do a wholesale insertion of colons. c) If the amount of repetition is controlled by parametric values, then you can adjust those values so that the amount of repetition is reduced during testing. For example, in Example 11.2.1.1, since the amount of repetition depends on the value of tol , you could initially set it to
a larger value such as 10K^3 and then set it to a lower value when you are convinced that things are probably running. In code given in Section 11.2.2, you could reduce the output in the initial execution trials by setting trackLength to a smaller number such as 20 Once you are confident that the repetition is working, you can set the parameters back to larger values. In the example, you could set it back to 100.
For problem (2), there are two tactics:
a) Interrupt the execution of the code region by clicking on the "red stop hand" in the Maple toolbar that becomes active when a script is running. This was explained in Section 8.1. b) Interrupt and inspect the state of execution by entering the Maple debugger. We discuss this latter tactic in the next section.
A "bug" is computer terminology for an error in a program. Finding and repairing bugs can take a lot of the programmer's time. Many bugs can be quickly found but some are quite subtle and may take longer to find. Finding mistakes in programs is one of the most difficult skills an introductory programmer learns, and it's mainly through trial and error under guidance from more skilled programmers.
First, have a clear idea of what is correct. Correct behavior by a script does not mean just the absence of error messages or warnings. Just because there are no error messages is not a sufficient sign that all is well -- the values being computed could be the wrong ones. For