Вы находитесь на странице: 1из 9

Chapter 1 2

Practical 3
In this practical sessio n yo u will learn ho w to ed it in ex isting fu nctio ns. N ex t yo u will d esig n fu nctio ns with fo r-statem ents. In this practical sessio n, yo u will practice the theo ry o f C hapter 4 u p to the while-statem ent o n pag e 44. S ave yo u r fu nctio ns in the le pract3 .x m cd .

12.1

E d itin g a n e x istin g fu n c tio n

In this part o f the co u rse we will sho w ho w to ed it an ex isting fu nctio n witho u t having to retype the fu nctio n ag ain. T his is particu larly im po rtant when m o ving statem ents to be co ntro lled by an if o r -later to be ad d ressed - fo r- o r whilestatem ent. P lease practice the ex am ple o n yo u r co m pu ter. A s a starting po int we will tak e the fu nctio n d epicted in F ig u re 1 2 .1 . In this fu nctio n ro o ts are calcu lated fo r the q u ad ratic fu nctio n ax2 + bx + c u sing the well-k no wn q u ad ratic fo rm u la. T he fu nctio n is a slig htly ad apted versio n o f the fu nctio n in F ig u re 3 .5 . T his fu nctio n can also yield co m plex ro o ts. S u ppo se we want a fu nctio n that o nly retu rns real ro o ts and retu rns z ero as bo th ro o ts are co m plex . S u ch a fu nctio n is g iven in F ig u re 1 2 .2 . T he transfo rm atio n fro m F ig u re 1 2 .1 to F ig u re 1 2 .2 will be d em o nstrated step-by-step. We will illu strate the transfo rm atio n pro cess in a certain o rd er. H o wever, it is po ssible to arrive at the sam e nal resu lt u sing ano ther o rd er o f steps. E nter the fu nctio n g iven in F ig u re 1 2 .1

ro o ts(a,b,c) :=

nu m 1 nu m 2 nu m 1 nu m 2

b+ b

2a
2a

b2 4ac b2 4ac

F ig u re 1 2 .1 : R o o ts o f a q u ad ratic fu nctio n 159

160

12 Practical 3

roots(a,b,c) :=

discr b2 4 a c if discr 0 num1 b+discr 2a b discr num2 2a otherwise num1 0 num2 0 num1 num2

Figure 12.2: Real roots of the quadratic function

roots(a,b,c) := num1 num2 num1 num2


b+ b

2a
2a

b2 4ac b2 4ac

Figure 12.3: The function after the rst step on a worksheet and exercise the following steps on your worksheet. D uring the transformation process we will not depict the editing line in the gures. Step 1 A quadratic function has real roots if the so-called discriminant is greater than or equal to zero. In order to test for this, the discriminant should be calculated separately. This should be done in the rst place, so on the rst line of the function denition. In the program the discriminant will be called: discr. The rst step is to insert a new line. Select the rst line of the function and enclose it fully in the editing line. If needed, press Insert to change from right- to left-editing line. Press A d d L in e on the Programming Toolbar to insert a placeholder before that statement. Figure 12.3 shows the result so far. Step 2 At the position of the placeholder the variable discr must be assigned the value currently under the root sign on line two. If the placeholder on line one is not selected, select it. Enter d i s c r and click from the Programming Toolbar. Place the left or right editing line around the expression under the root. Probably M athcad raises the error message: This placeholder is empty . To remove this error message: type E sc . If just a part of the expression under the root is selected, type S p a ceb a r one or more times. Click C u t on the Standard Toolbar. A placeholder under the root sign is caused by this last action. The placeholder may be

12.1 Editing an existing function

161

roots(a,b,c) :=

discr b2 4 a c num1 b+ 2a b2 num2 b 2a4ac num1 num2

Figure 12.4: The function after the second step discr b2 4 a c num1 b+discr 2a b discr num2 2a num1 num2

roots(a,b,c) :=

Figure 12.5: The function after the third step colored red and display an error. Do not pay any attention to this. Select the placeholder on line 1 and click the Pa ste of the Standard Toolbar. Figure 12.4 shows the result. Step 3 Enter discr under the root sign. Next, replace the expression for the discriminant in the assignment statement for num2. So, enclose the expression under the root sign in the left or right editing line, click Cut of the Standard toolbar to erase the expression, and enter discr. This results in Figure 12.5. Step 4 The assignment statements for num1 and num2 should be placed under control of an if-statement. Firstly, we need some more space. Therefore, select the rst line in Figure 12.5, enclose it fully in the right editing line, and click Add Line on the Programming Toolbar. We insert an if statement at the position of the placeholder by clicking if of the Programming Toolbar. Select the placeholder to the right of the if and enter: discr0. The symbol can be found on the B oolean Toolbar. Figure 12.6 shows the result. Step 5 B oth assignment statements should be positioned under control of the if-statement on line three and four, so there we need an extra line. Therefore, select the placeholder to the left of the if and click Add Line on the Programming Toolbar. This leads to Figure 12.7 . Step 6 It is not possible to move the two statements in one action so the statements must be selected and moved one at a time. Select the rst statement, which is the statement that assigns the variable num1 a value

162

12 Practical 3

roots(a,b,c) :=

discr b2 4 a c if discr 0 num1 b+discr 2a b discr num2 2a num1 num2

Figure 12.6: The function after the fourth step roots(a,b,c) := discr b2 4 a c if discr 0 num1 b+discr 2a b discr num2 2a num1 num2 Figure 12.7: The function after the fth step and enclose it with an editing line. Click Cut of the Standard Toolbar. A placeholder appears in stead of the statement; we will deal with it later. Select the placeholder on line three and click Paste of the Standard Toolbar. Move the second statement in a similar manner to line four. Figure 12.8 shows the result so far. Step 7 The otherwise-statement should be positioned on line 5. Select the placeholder on line 5 and click o th erw ise on the Programming Toolbar. Since two statements should be located under the otherwise section, another line should be added. Therefore, select the placeholder to the left of otherwise and click Add Line of the Programming Toolbar. Enter num1 0 on the rst placeholder and enter num2 0 on the second one. Figure 12.9 shows the result. Step 8 O ne placeholder is still present but not needed. So, select the redundant placeholder and press Back Space to remove it. Now the function has been completely transformed. Your worksheet should be similar to Figure 12.2. Cut and Paste of the Standard Toolbar or of the E dit of the Main Menu work on the part of the worksheet that is enclosed by the editing line. Reasonable is to expect that the same holds for D elete of E dit. However, that is not the case. Clicking D elete deletes the part of the worksheet that is enclosed by the

12.2 Repetitions

163

roots(a,b,c) :=

discr b2 4 a c if discr 0 num1 b+discr 2a b discr num2 2a num1 num2

Figure 12.8: Function after sixth step discr b2 4 a c if discr 0 num1 b+discr 2a discr num2 b a 2 otherwise num1 0 num2 0 num1 num2 Figure 12.9: Function after seventh step rectangle formed by the black lines. If you are editing a function, the complete function falls into the rectangle. Clicking Delete will delete the complete function, so be carefully!

roots(a,b,c) :=

12.2

R ep etitions

In programming functions, frequently we need to repeat some instructions. In Mathcad two so-called loop-statements are available: for- and while-statement. Which one to apply depends: The loop terminates when a condition is fullled. Beforehand it is not known how many iterations are needed. Apply the while-statement. Beforehand it is known how many iterations are needed. Apply the forstatement. In this practical session you will learn how to enter a for-statement in a function and you will design some functions with the for-statement. The while-statement will be discussed in another practical session.

164

12 Practical 3

12.2.1

Fo r-sta te m e n t

A for-statement is inserted if you select a placeholder and click for of the Programming Toolbar. You will see a structure like: for

The so-called iteration variable should be inserted in the placeholder left to the symbol. This variable will be incremented by one each time the computer executes the loop. In the placeholder to the right of the symbol a range can be inserted. A range, for example 1..7, is inserted by typing 1 ; 7 . Notice that because of entering ; two succeeding dots are displayed. With, for example, the range 1..7, the iteration variable will be incremented by one. For another step size, for example 2, you should enter 1 , 3 ; 7 leading to: 1, 3..7. This range can be replaced by a vector, a list of numbers, or variables (except matrix variables) and vectors separated with commas. In the case a vector or a list of vectors has been listed all the elements of the vector or the list of vector(s) will be addressed. The last placeholder can be used to insert a statement. If many statements should be included in the for-statement then place the editing line around the last placeholder and click Add Line of the Programming Toolbar. This will look like: for

If you know beforehand that you need to enter several statements in the for-loop you can create several new lines with a placeholder. However, if you have to add one or more lines to a for-loop with one statement in it, you should proceed as follows. Select the statement in the for-loop and click Add Line of the Programming Toolbar. A vertical bar appears with to the right of the bar the existing statement and a new placeholder. So, this operates like it operates for an if- or otherwise-statement. If you need to insert more lines, just repeat clicking Add Line as many times as necessary. In case you like to enter a statement before the rst statement in a for-loop you can do the following. Enclose the rst statement with the left 1 editing line and click Add Line. A new line with a placeholder will result. If you need to add a new line following the last statement in the for-loop then you enclose the last statement in the loop with the right editing line and click Add Line. You may enclose more than one statement in the for-loop, however enclosing the complete for-statement will generate a new line outside of the for-loop.

12.3

H ow th e for-statem ent operates

Before you start to make some assignments with for-statements, we will illustrate the way the for-statement operates. We do that with some tools Mathcad
1

Switch in g fro m rig h t to le ft e d itin g lin e a n d th e re v e rse by Insert .

12.3 How the for-statement operates

165

sum1toN(N) :=

sum 0 pause(N = {0},sum = {1},N,sum) for i 1..N sum sum + i pause(i = {0},sum = {1},i,sum) sum

Figure 12.10: Computing sum of 1 up to and including N with calls to pause

Figure 12.11: The Debug Toolbar provides for nding errors in programs. Enter the function given in Figure 12.10 on a worksheet. In this function you see a call to the function pause. In this call you need to enter two double quotes. Pay attention to the fact that if you enter then Mathcad enters two double quotes on your worksheet. The editing line is between these double quotes, so you may enter the text to be written within these quotes. After you have entered sum=1, rst you have to go one position to the right before you enter the remaining part of the call. The remaining part should not be within the double quotes. L ater you will learn what the purpose of the function pause is. To illustrate how the for-statement operates we need the Debug Toolbar. See Figure 12.11 for a picture of the the Debug Toolbar. The Debug Toolbar is positioned at the top of the Mathcad window. If there is no Debug Toolbar in your Mathcad window, do as follows. Select View of the Main menu, select Toolb ars and select Deb ug . If you click another time on Deb ug then the Debug Toolbar disappears. For now we leave the Debug Toolbar in the Mathcad window. The Debug Toolbar contains four buttons. In this demonstration we will use, counting from the left, the rst (Resume button) and the third (Toggle Debugging button) buttons. Click on the Toggle Debugging button. If you do not have a Trace Window in the Mathcad window, it will appear automatically. Soon you will learn what the Resume button does. On your worksheet enter after the denition of the function sum1toN(5)=. The computer starts now with executing the instructions in the function sum1toN. The computer stops after it has executed the rst call to the function pause. The call of pause displays the values of the variables N and sum in the Trace Window. Examine the values of N and sum. Are these values correct? Take your time, Mathcad waits for an order to continue. If you are ready with examining, click on the Resume button of the Debug Toolbar. The computer resumes working on the function. All instructions up to and including the second call of the function pause will be executed this time. Mathcad displays now the values of the variables i and sum in the Trace Window. Examine whether the displayed values are according to what you expect. Again click on

166

12 Practical 3

the Resume button of the Debug Toolbar. Another time examine the values of the variables. Is it correct that you get values of the variables i and sum? And are these values correct? Click on the Resume button another time. Are the values in the Trace Window correct? Continue to click on the Resume button until the function is ready. The function is ready when on your worksheet there is the answer (15) after the =-symbol. Count the number of times there are values for the variables i en sum. Is this number correct? Because you will not use the debug facilities during the remaining part of this practical session you may click on the Toggle Debugging button of the Debug Toolbar. You may remove the Debug Toolbar and Trace Window as well. By doing so, your worksheet becomes somewhat larger.

12.4

A ssignments

In this practical session we will work with vectors. It is easy to make errors when working with vectors, so the function you prepares may not produce the right result. Often it is di cult to nd the cause for the error. The Trac e Error option may be helpfully, see for more information page 38. 1. Raising a number to a power is simple using the ^ operator. Assume that operator is not operational. It is possible to simulate the power-operator by designing a power function by repeated multiplication. For instance x5 = x x x x x. The for-statement can do the repetition. Write a function with the name power that calculates the power of any number by repeated multiplication. Assume that the power is a positive and integer number. Show that your function is working and also write an alternative function as is described in the hints. H ints: (a) The function will take two arguments: the power and the argument that should be raised to that power. The call of the function to calculate, for example 24 will be power(2,4). (b) Do not use the power of operator ^ or x y of the Calculator Toolbar of the Math Toolbar. (c) To calculate result = x5 you can start to assign 1 to result. In the loop you can assign result the value of result x. How many iterations are needed? Convince yourself that the answer is correct. As an alternative, you can assign x to result. Does this have an implication for the number of iterations needed? Also, write a function using this alternative. (d) To formulate a for-statement one needs a so-called iterator. For example, in for i 1..3 is i the iterator. In the theory chapters and in later assignments, you will meet assignments where the iterator is used in one or more instructions that are repeatedly executed. In this example, the iterator is not used in such an instruction. So, in

12.4 Assignments

167

the function you will formulate, the iterator is just for the purpose of formulating the repetition. 2. Write a function that adds all even numbers between 1 and n. There are two methods available for your design: (a) Construct a for-loop starting at 2 and addressing only the even numbers. So 2, 4, 6, . . . . (b) Address all numbers between 1 and n and check whether the number addressed is even. A number is even if it is divisible by 2. This is true if the call mod(x,2) returns zero. The function mod is available in Mathcad, please refer to its description in the on-line list of functions or check the Insert function window after clicking Function... of Insert of the Main Menu. Write the function in two versions using the methods as mentioned. 3. Write a function that calculates the sum of elements of a given vector. So, for a vector with elements 1, 3, 7, 10 the result of your function should be 21. Hint: (a) In this function you will address successive elements of the vector. Element i of the vector v can be addressed by pressing v [ i . Do not use the literal subscript. See page 15 and Section 2.6 on page 17 for more information. (b) Function last might help you here. See for details and use page 36. 4. Write a function that nds the maximum value of the elements of a vector. Return the maximum value and its position in the vector. Hints: (a) Take advantage of what you have learned from the algorithm to determine the largest of some values, see page 27 and following pages. Adapt this algorithm using a for-statement and addressing vector elements in stead of scalar variables. (b) Like in the preceding assignment, function last might help you here. See for details and use page 36.

Вам также может понравиться