CC3 -- The Calculus Calculator Copyright 1989 David Meredith Department of Mathematics San Francisco State University 1600 Holloway Ave. San Francisco, CA 94132 415-338-2199/2251 This preliminary manual documents the developing product CC3. You are encouraged to use CC3 and report bugs and suggestions to me. However I do not offer the program as yet sufficiently debugged for significant calculations without careful double- checking. I welcome letters and telephone calls with complaints and suggestions for improving CC3. Talking to other users is the only way I can improve my program, so I am always willing to answer questions about CC3. I am especially interested in hearing about classroom uses of CC3. Feel free to share it with your students. CC3 is shareware. If you use it, a donation of $25 to the Applied Mathematics Fund, Department of Mathematics, SFSU would be appreciated. 1 CC - The Calculus Calculator Oct 27, 1989 Table of Contents I. Using the Calculator I.1 Mathematical calculations I.1.1 Numbers and arithmetic I.1.2 Algebraic functions I.1.3 Transcendental Functions I.1.4 Other Functions I.1.5 Binary and Hexidecimal Numbers I.2 Variables I.3 User-defined functions I.3.1 Differentiation I.3.2 Integration I.3.3 Solving equations I.3.3.1 Solving systems of equations I.3.3.2 Defining functions implicitly I.3.3.3 Differentiating implicit functions I.3.4 Tables of function values I.3.5 Sums and products I.3.6 Slope of secants I.4 Graphing functions I.4.1 Cartesian graphs 1.4.2 Graphing derivatives and integrals I.4.3 Polar graphs I.4.4 Parametric graphs I.4.5 Line styles and colors I.4.6 Three-dimensional graphs of surfaces I.4.7 Saving and printing graphs I.5 Lists and arrays I.5.1 Entering lists I.5.2 Accessing lists I.5.3 Modifying lists I.5.4 List operations I.5.4.1 Vector operations I.5.4.2 Lists and statistics I.5.4.3 Graphing lists I.5.4.4 Printing lists 2 CC - The Calculus Calculator Oct 27, 1989 I.6 Odds and ends of Calculator usage I.6.1 Using Help effectively I.6.2 Using the printer I.6.3 Saving and loading work from disk I.6.4 Controlling output precision I.6.5 Controlling precision of Integration and solving operations I.6.6 Monitoring memory usage II. Programming CC3 II.1 How to use the Scratchpad II.2 Procedures and functions II.2.1 Functions as parameters II.3 Program flow control II.3.1 Comparison operators II.3.2 Logical operators II.3.3 Conditional statements II.3.4 Loops II.4 Special programming operations II.4.1 Writing output II.4.2 Obtaining user input II.4.3 Strings II.4.4 Graphics programming II.4.5 Sound III. Recursive Definitions in CC3 III.1 Scratchpad Procedures and Functions III.2 Variables III.3 Single-line function definitions 3 CC - The Calculus Calculator Oct 27, 1989 These notes assume that you will read them while using CC3. On occasion you will be instructed to type something into the Calculator to illustrate a point. I. Using the Calculator To start CC3, put the disk in the current drive and enter the command CC3. You will see a message warning you that you are using a preliminary version of the program. Push any key to clear the screen and start calculating. To enter a formula into the Calculator, you just type it and press . You can use the cursor keys to correct your formula with the usual IBM conventions. The Insert key toggles the Insert/Overwrite mode; the default is Insert. Try entering the formula 3 + 4 You will see the answer in two places; the Last Result window at the bottom of the screen and next to ANS in the Output window. Use the arrow keys to move the cursor to "+"; change it to "/" and press enter. The new formula will be calculated. As you use CC3, you are not limited to entering a series of formulas. You can always cursor back to a previous formula, modify it if desired, and re-execute it by pressing . You can enter lines that are longer than the width of the input window. Just keep typing, and your entry will continue on succeeding lines, indented one space. You can have up to 255 characters in an entry. You can open up free lines in your list of formulas by pressing the function key F3. You can erase a line by pressing Shift-F4. You can erase ALL the lines you have entered (including the Scratchpad--see part II below) by pressing Shift-F10. You can add comments to a line in CC3, or even produce a line which is entirely a comment, by preceding the comment part with two slashes // . For example: 3 + 4 // My first calculation Comments make your calculations more understandable, whether you are making a printed record of what you are doing or if you just want to jot some notes to yourself while you are working. 4 CC - The Calculus Calculator Oct 27, 1989 I.1 Mathematical calculations CC3 is ultimately a programming environment optimized for mathematical calculations. For most purposes, however, you do not need to use the programming feature at all. You will just perform enter single-line calculations by typing in the formula you want to evaluate and pressing . The formulas can be up to 256 characters long and can include parentheses nested to any depth. I.1.1 Numbers and Arithmetic CC3 accepts integer and real numbers in most conventional formats. You can enter 2, 20, 0.2, .2, -2, -0.2, -.2, etc. You can also enter numbers in exponential format: 2e5, .02e-5, etc. The five basic arithmetic operations are available in CC3: + Addition - Subtraction * Multiplication / Division ^ Exponentiation 2 For example, to compute 2(3 + 4), enter 2*(3^2 + 4). Exponentiation precedes multiplication and division, which precede addition and subtraction. Otherwise operations are performed left to right. These are the usual algebraic conventions. Exponents can be any real numbers, even if the base is negative. Thus you can enter (-2)^(0.5) . Try it. CC3 can calculate with complex numbers as well as real numbers. Complexes can be used in all operations and as arguments for all functions. As we see below, you can even integrate and differentiate with complex numbers, and you can solve equations for complex roots. Try the following formulas: (2 + 3*i) / (4 - 5*i) i^i Note that 2+3i is incorrect; you must enter 2+3*i. Calculations with undefined results are not treated as errors; they just produce the result UNDEFINED. UNDEFINED is a number in CC3, albeit with some strange properties. You can even enter this number directly; just enter UNDEFINED (this might be useful in a program if you wanted to test if the outcome of a calculation was defined or not). Try entering 1/0 to see an undefined result. Can you find any other undefined formulas? 5 CC - The Calculus Calculator Oct 27, 1989 In addition to i and UNDEFINED, CC3 includes the built-in constants PI, TRUE, and FALSE. TRUE and FALSE will be discussed in Part II; PI just means 3.14159.... . I.1.2 Algebraic functions CC3 has the following functions operating on real and complex numbers: function meaning example SQR square SQR(3) SQRT square root SQRT(5) ABS absolute value ABS(-3) RE real part RE(4 - 3*i) IM imaginary part IM(4 - 3*i) ROOT integer root ROOT(3,5) NB: Both ROOT(3,5) and 3^(1/5) produce the same real 5'th root of 3. To get a complex 5'th root of 3, use 3^(1/5)*EXP(2*PI*i/5) . (See I.1.3 for EXP, the exponential function.) I.1.3 Transcendental Functions CC3 has all standard exponential functions, which can be used on real and complex numbers. The branches of the complex functions have been selected so that the inverse functions work correctly when possible. Trig and inverse trig functions: SIN, COS, TAN, COT, SEC, CSC, ATAN, ASIN, ACOS Hyperbolic and inverse hyperbolic functions: SINH, COSH, TANH, ATANH, ASINH, ACOSH Exponential and logarithmic functions: EXP, LN 3 EXP(3) means e . Note that e is NOT a built-in constant in CC3. If you need it, use EXP(1). 6 CC - The Calculus Calculator Oct 27, 1989 I.1.4 Other Functions function meaning example INT integer part INT(3.4) FRAC fractional part FRAC(3.4) DIV integer division 18 DIV 4 MOD remainder 18 DIV 4 PAR parity PAR(5) FACT factorial FACT(17) BINOM Binomial coefficient BINOM(5,3) RANDOM Random number RANDOM RANDOM(4) Notes: INT works on complexes too; it returns Gaussian integers; DIV and MOD work only on positive integers. n PAR(n) means (-1) . It is useful in defining power series (cf. I.3.5). RANDOM with no arguments returns a random real in the range (0,1); if n is a positive integer, RANDOM(n) returns a random integer in the range 0..n . Future versions of CC3 will also include the function LNGAMMA to extend FACT. I.1.5 Binary and Hexidecimal numbers You can calculate binary and hexidecimal numbers in CC3. To enter a binary number, precede it with #: #110001101 ; to enter a hexidecimal number, precede it with $: $3a24 . Numbers up to 32 bits (8 hex digits) may be entered. They are retained as positive 32 bit constants, so -$2 becomes $FFFFFFFE. These numbers can be added and multiplied, and even divided. When it would not make sense to treat them as integers, they are transformed to reals. To transform one of these numbers to another form, use the functions: INTEGER(x) returns integer value of x HEX(x) returns x in hex form BIN(X) returns x in binary form Integer, hex and binary numbers can be combined with AND and OR, and you can apply the function NOT to them. Note that NOT(x) = - x - 1 . 7 CC - The Calculus Calculator Oct 27, 1989 I.2 Variables Variables are used to store the results of calculations. Variable names must start with a letter and use only letters and numbers. They can be up to 12 characters long, and they are not case sensitive. To assign a result to a variable, just put = before the expression to be evaluated: a = 2 + 3 // assign value to a Variables and their values are listed in the Output window. Variables can be used like constants in expressions. For example: a = 2 + 3 b = a*4 If an undefined variable is used in an expression, then the expression returns a symbolic result (which may be stored in another variable). Pick an undefined variable name, say x, and enter: 8 CC - The Calculus Calculator Oct 27, 1989 y = 3 + x // formula results since x undefined x = 4 // Now x is defined y // y returns 7, but its value is // still the formula 3 + x x = 7 // revalue x y // new value for y Symbolic values for variables are useful mostly for viewing the definitions of functions and derivatives. See (I.3, I.3.1). Watch out for infinite recursion here. Defining a = a+3 when a has no initial value will not cause an immediate problem, but any future reference to a will result in an infinite recursion! (Cf. Part III below.) If a variable does not appear in the output window, use the scrolling keys F5 and F6 to bring it into the window. If you want to suppress the display of a variable (this might be the case if the variable was a list--cf. I.5), enter the command: HIDE(v) where v is the name of the variable you don't want to display. To restore the variable to the display, issue the command: SHOW(v) Variables are still defined whether or not they are displayed. You can eliminate a variable--undefined it that is--with the command: FORGET(v) where v is the name of the variable. This command will also eliminate a function definition (cf. I.3 below). I.3 User-defined functions You can enter your own functions into CC3. Just type them as you would ordinarily write them: f(x) = sin(2*x) g(x,y) = x^2 - y^2 Once defined, functions can be evaluated or used in expressions: a = f(PI/3) b = SQRT(g(4,a)) 9 CC - The Calculus Calculator Oct 27, 1989 Function names satisfy the same conventions as variable names. You can define a function with no variables: f() = random+random+random+random+random The parentheses must appear to distinguish the function f() from the variable f (which would be given a single numerical value). Once defined, f() can be referred to either as f() or f . The example is an approximation to to normally distributed random variable with mean 2.5 and variance 5/12. I.3.1 Differentiation CC3 differentiates symbolically. If f(x) is an expression using the variable x, you can differentiate it with respect to x and evaluate the result at x=a with the command D(f(x),x=a). Here are some examples you can try: D(sin(2*x),x=PI/2) f(x) = exp(x) D(f(x+3),x=0) Note that the differentiated expression can include user-defined functions. You can also define a function to be the derivative of an expression: g(t) = D(sin(2*x),x=t) This line can be shortened to: g(x) = D(sin(2*x),x) To view the derivative of an expression, set the variable of differentiation equal to an undefined variable, so that the derivative does not evaluate to a constant: D(sin(x^2),x=u) // assumes u is undefined User-defined functions that include integrals, solve, slope, sum, or product (see below) can be differentiated. CC3 knows the derivatives of these operators. When these notes are expanded, I'll include an essay on the expression D(f(x),x) and what it means about the logical status of the variables in CC3. I'll just add one thing here. If you define a = 3 + exp(x) 10 CC - The Calculus Calculator Oct 27, 1989 where x is an undefined variable, then the expression D(a,x) won't return exp(x) . In D(f(x),x), the variable x must appear explicitly in the expression f(x). Only explicit occurances of x are differentiated in f(x). Indirect references to a variable x are not recognized. I.3.2 Integration To integrate an expression f(x) for a < x < b, enter the formula IN(f(x),x=a,b) or IN(f(x),x = a TO b). The integration is carried out numerically using an adaptive Simpson's algorithm. For example: p = IN(sin(x),x=0,PI) q = IN(f(x),x=0,1) // assumes f(x) is defined You can defined functions using integrals. The bound variable in the function can appear in the integrand or the limits of the integral. These functions may be slow to evaluate, but they can be defined. f(x,y) = IN(1/t, t = x TO y) g(x) = IN(f(t-x), t = 0 TO 1) If CC3's integral calculation does not converge after a specified number of subdivisions, the best answer is returned along with a warning that the answer may not be trustworthy. To see this, try the following two integrals: a1 = IN(1/x,x=0,1) a2 = IN(1/sqrt(x),x=0,1) Of course, the first integral does not converge and the second does. To check the accuracy of a questionable integral, split the domain of integration into two parts and compare the answers to the unsplit domain: a3 = IN(1/x,x=0,0.1) + IN(1/x,x=0.1,1) a4 = IN(1/sqrt(x),x=0,0.1) + IN(1/sqrt(x),x=0.1,1) You can speed up the operation of integration, at the expense of accuracy, by replacing IN with FIN (Fast INtegration). Use FIN in place of IN when defining functions using integrals that you want to graph. To adjust more precisely the factors controlling the accuracy of the integration calculation, see (I.6.5). 11 CC - The Calculus Calculator Oct 27, 1989 I.3.3 Solving equations To solve the equation f(x) = g(x) for x, enter the expression SOLVE(f(x)=g(x),x=a) where a is your best guess for a root. CC3 uses Newton's method to solve equations, so it can solve for complex as well as real roots. As always, f(x) and g(x) can be combinations of built-in functions and user-defined functions. For example, to find the solution to cos(x) - x = 0 , just enter: SOLVE(Cos(x) - x = 0, x = 1) The solution to the equation is stored in the variable x. Since CC3 uses Newton's method, a bad first guess can cause it to miss the root. To avoid this problem, first graph the function you want to solve (I.4) and use the graph to pick an approximate root. If the function is concave down where its graph passes through the x-axis, then pick an approximate root to the left of the actual root; if the graph is concave up, then pick the approximate root to the right of the actual root. If your equation is extremely complicated, and if you do not need a very precise solution, you can speed up the solving process at the expense of accuracy by replacing SOLVE with FSOLVE (FastSOLVE). You can also modify the factor controlling the convergence tests in the solving algorithm for more or less accuracy or speed (I.6.5). I.3.3.1 Solving systems of equations The SOLVE operator can be used on systems of equations exactly like it is used on a single equation. You may enter up to eight equations, and you must specify as many variables as equations, each with an initial value. For example, to solve the system: 2 3 2 x + y + z = 3 2 2 3 x - y - z = 0 3 2 2 x + y - 2z = 0 for the root nearest (1,1,1), you would enter the line: SOLVE(x^2+y^3+z^2=3,x^2-y^2-z^3=0,x^3+y^2+2z^2 =1, x=1, y=1, z=1) The SOLVE operator will assign the solutions of this system to the variables X, Y, and Z. 12 CC - The Calculus Calculator Oct 27, 1989 I.3.3.2 Defining functions implicitly Generally speaking, an equation in two unknowns can be said to define either of the unknowns as a function of the other. For example, the equation: x^2 + r*x - 3 = 0 defines x as a function of r . In practice, the equation may have more than one solution x for each choice of r , but if we begin with an approximate value (initial guess) for the solution, there will be a single solution x closest to the selected approximate value. For example, if we wanted to find the solution closest to x = 2 when r = 2 , we could enter: SOLVE(x^2 + 2*x - 3 = 0, x=2) The result will be x = 1 . However, this expression fails to capture the functional nature of x with respect to r . CC3 has an operator IMPLICIT that allows you to define x as a functions of r as follows. The IMPLICIT operator uses the same arguments as the SOLVE operator, but whereas SOLVE is a procedure that places its results in specified variables, IMPLICIT is a function (like SIN) that returns its result as a value). If you enter: IMPLICIT(x^2 + 2*x - 3 = 0, x=2) the result 1 is placed in the variable ANS. If you enter: a = IMPLICIT(x^2 + 2*x - 3 = 0, x=2) then the variable a gets the value 1 . To define x as a function of r , enter; g(r) = IMPLICIT(x^2 + r*x - 3 = 0, x=2) If you now enter: a = g(2) you will get the result a = 1 . You can treat g(r) just like any other function of one variable. You can graph it, integrate it, differentiate it, integrate it, etc. Note however that when you graph a function or integrate it you must evaluate the function many times over. Since IMPLICIT can be much slower to evaluate than a function like SIN , you should use FIN in place of IN for integration and SKETCH in place of GRAPH for graphing. See also I.6.3 for information about speeding up IMPLICIT by changing the factor SolveTolerance. 13 CC - The Calculus Calculator Oct 27, 1989 IMPLICIT can be used to define functions of more than one variable, for example: g(r,s) = Implicit(x^2+r*x + s = 0, x = 2) IMPLICIT can also be used to define implicit functions with more than one equation. Consider, for example: a = IMPLICIT(x*y = 3, x - y = 2, x=1, y=1) This expression must return two values, 3 and 1. But these must be returned in the variable a, so IMPLICIT returns a as a list (cf. I.5 for information about lists) with a[1] = 3, a[2] = 1. Similarly, the expression: g(r,s) = IMPLICIT(x*y = r, x - y = s, x=1, y=1) defines a function g(r,s) whose values are lists of two elements. If you enter: a = g(3,2) you get a[1] = 3, a[2] = 1. The function g(r,s) can be graphed, integrated, differentiated, etc. like any other function of two variables. I.3.3.3 Differentiating Implicit Functions Functions defined implicitly can be graphed, integrated, tabulated (I.3.4), solved and differentiated just like any other functions, although you should remember that implicit functions may be quite slow to evaluate. I want to add a word here about the form of the derivative of an implicit function. I will discuss a two examples and leave it to the reader to extrapolate to the general case. The first example we will consider is the one above: g(r) = IMPLICIT(x^2 + r*x - 3 = 0, x=2) Differentiating g(r) with respect to r requires no special commands. Just enter: a = d(g(r),r=2) You will get: a = -0.25 The ambitious reader may solve the implicit equation for g(r) explicitly and differentiate it to check this result. If r is an undefined variable and you enter: 14 CC - The Calculus Calculator Oct 27, 1989 a = d(g(r),r) you will get the formal derivative of g(r) with respect to r; it is the form of the derivative of g(r) when g(r) is an implicit function that we wish to explain. If you entered the derivative, you saw the resulting formula: a = IMPLICIT(-2+X^2+R*X = 0, X + 2*X*ZZZ1 + R*ZZZ1 = 0, X = 3, ZZZ1 = 0)[2:2] That means that the derivative of g(r) is the second component (the variable ZZZ1) of the solution of the system of equations: 2 X + R*X - 2 = 0 X + 2*X*ZZZ1 + R*ZZZ1 = 0 This system of equations is just the original equation: x^2 + rx - 2 = 0 and its derivative: 2*x*(dx/dr) + x + r*(dx/dr) = 0 Solving this system for any particular value of r results in both the value of g(r) and the value of dg/dr for that value of r. By appending the sublist selector [2:2] to the end of the IMPLICIT operator, we choose only the value for the derivative from the two values produced by IMPLICIT. For our second example, we use the function of two variables above: g(r,s) = Implicit(x^2+r*x + s = 0, x = 2) First we will calculate the derivative of g(r,s) with respect to r at the point (r,s) = (3,2): a = d(g(r,2),r=3) The result is a[1] = 0.25 a[2] = 0.25 There are two results because g(r,s) is a function that returns a list of two values, so it is really two scalar functions. Its derivative with respect to r is thus the scalar derivatives of two scalar functions. To see the form of the formal derivative of g(r,s), make sure that r and s are undefined and enter: 15 CC - The Calculus Calculator Oct 27, 1989 d(g(r,s),r) The result is: IMPLICIT(X*Y = R, X-Y = S, -1+Y*ZZZ1+X*ZZZ2 = 0, ZZZ1 + (-ZZZ2) = 0, X = 1, Y = 1, ZZZ1 = 0, ZZZ2 = 0)[3:4] That is, the formal derivative of g(r,s) is a system of four equations in four unknowns, from which we will select the last two solutions ZZZ1 and ZZZ2. These equations are just the two original equations together with their derivatives with respect to R. ZZZ1 and ZZZ2 correspond to the derivatives of X and Y with respect to R respectively. The largest number of equations that can appear in a system of equations in CC is 8; so the largest number that can appear in a function to be differentiated is 4. I.3.4 Tables of function values If you want to look at a table of values for a formula, you can use the TABLE command. The command TABLE(f(x),x=a to b step dx) causes a table of values for f(x) to be displayed with x=a, a+dx, ..., b. You can specify one or two functions to be in your table, for example: TABLE(Sin(x),x=0,PI/2,PI/40) TABLE(Sinh(x),Cosh(x),x=0,1,0.1) I.3.5 Sums and Products With CC3 you can compute finite sums and products and construct functions like Taylor polynomials or finite Fourier series. The procedure is the same for sums as products (except the empty sum evaluates to 0, and the empty product to 1), so all examples will be restricted to sums. The general format for these operators is: SUM(f(x),x=a to b step c) PROD(f(x),x=a to b step c) The expression f(x) is evaluated at a, a+c, ... up to the last entry in the series not greater than c, and the resulting values are added or multiplied. The part "Step c" is optional and defaults to 1. Here are some examples: 16 CC - The Calculus Calculator Oct 27, 1989 SUM(j,j=1 to 10) // 1 + 2 + .. + 10 SUM(3^j, j = 0 to 10 step 2) // 1 + 3^2 + ... + 3^10 Here are some sample Taylor polynomials: e(x,n) = SUM(x^j/fact(j), j = 0 to n) // exp(x) s(x,n) = SUM(Par(j)*x^(2*j+1)/fact(2*j+1),j=0,n) // sin(x) of degree 2n+2 j Remember, Par(j) = (-1) and Fact(j) = j! . The words TO and STEP can be replaced by commas. I.3.6 Slope of secants Sometimes it is useful to determine the slope of the secant line through two points on the graph of a function. That is the slope of the line through (a, f(a)) and (b, f(b) . You can calculate this directly with the command: SLOPE(f(x),x=a,b) I.4 Graphing functions CC3 includes extensive facilities for graphing functions. Before you graph any function on the plane, you must specify the size of the visible screen with the command: WINDOW(a,b,c,d) The expressions a,b,c,d must evaluate to real numbers (they can be real numbers themselves) such that a < b and c < d. This command tells CC3 that the visible screen corresponds to a portion of the xy-plane with a <= x <= b and c <= x <= d. When CC3 starts there is a default window in place: WINDOW(-1.4,1.4,- 1,1) . If you want your circles and squares to look correct-- that is, if you want one vertical unit to be really the same distance as one horizontal unit--you should select window parameters so that the horizontal axis is 1.4 times as long as the vertical axis. If CC3 attempts to graph a point (x,y) which is outside the window, it ignores the point and continues. No error message is generated, and even functions which are undefined on part of the graphing domain can be graphed. You can resize the graphics window at any time, but doing so erases the screen. You can also erase the screen without resizing the window with the command: ERASE 17 CC - The Calculus Calculator Oct 27, 1989 In between erasures or resizing, each graph is drawn on top of the previous graphs, so graphs of functions can be compared. On color screens successive graphs are different colors; on monochrome screens they use different line styles (but if the points where they are computed are too close together, the different line styles all look the same). The WINDOW command does not effect the graphs drawn by HISTOGRAM (I.5.4.2) or GRAPH3D (I.4.4), but it does control the visible portion of the result from LISTG (I.5.4.3). Three general conventions about graphing: 1. A graphing process (or any other process in CC3) can be interrupted safely at any time by pressing the key. 2. The last graphics screen constructed can always be recalled by pressing function key F9. See I.6.6 for more information on how this operation affects memory utilization. 3. Most graphics screens include crosshairs with coordinates. You can move these about the screen, using the arrow keys for gross movements and the shifted-arrow keys for fine movements, and so find the coordinates of any point on the screen. If you are using an extended keyboard, then use the keys "2", "4", "6" and "8" for the shifted-arrow keys. I.4.1 Cartesian graphs To graph the expression f(x) with respect to x, just use one of the commands: GRAPH(f(x),x) DOTGRAPH(f(x),x) QUICKG(f(x),x) SKETCH(f(x),x) These commands all produce the graph of f(x), but in slightly different ways. GRAPH computes a value of f(x) for x corresponding to every pixel on a horizontal line across the screen, and then connects the resulting points (x, f(x)). DOTGRAPH computes the same points but just plots them without connecting them with lines. For most graphs there is little difference, but DOTGRAPH does not make phony connections across singularities. QUICKG works like GRAPH but only computes values for every third pixel. Hence the name. SKETCH is similar but only computes values for every 20'th pixel. Use SKETCH if the function you want to graph is very slow to compute. You can put a cross on a graph to mark a single point (a,b) with the command MARK(a,b) 18 CC - The Calculus Calculator Oct 27, 1989 This is useful for marking data points in connection with linear regression. 1.4.2 Graphing derivatives and integrals You can graph the tangent line to a curve f(x) at the point x = a with the command DIFFG(f(x),x=a) DIFFG works exactly line the derivative operator D; it returns the derivative f'(a). But it also draws the graph of f(x) on the screen and, if (a, f(a)) is in the graphics window, it draws the tangent line to the curve at this point. Try the command: DIFFG(x^2, x = 1/2) You can also highlight the area corresponding to an integral. The command: INTEG(f(x),x=a,b) returns the integral of f(x) for a <= x <= b , and it also causes the graph of f(x) to be drawn and the area between the curve and the x-axis to be highlighted. Actually, a vertical line is drawn between the curve and the x-axis for each value of f(x) that is computed for the integral. By watching INTEG, you can see exactly how CC3's adaptive Simpson's algorithm works. Here's an interesting one to try: WINDOW(0,1,0,10) INTEG(1/sqrt(x),x=0,1) CC3 makes more calculations at the left end of the interval than the right in an attempt to produce an accurate integral. I.4.3 Polar graphs To graph the function r = f(theta) in polar coordinates, you must first define a window in rectangular coordinates to hold your graph. Then issue the command: POLARG(f(t),t = a,b,n) CC3 will graph r = f(t) for a <= t <= b using n steps (n+1 points). For example: WINDOW(-1,2,-1.5,1.5) POLARG(1 - Cos(t), t = 0, 2*PI, 100) // cardoid 19 CC - The Calculus Calculator Oct 27, 1989 CC's ability to sense when a graph has already been drawn can have drawbacks. PolarG is useful for drawing polynomials, even self-intersecting polynomials, as with the following sequence of commands: POLARG(1, t = 0, 2*pi, 5) ERASE POLARG(1, t = 0, 6*pi, 5) However, try the following commands. CC3 thinks the second is a repeat of the first so it won't draw it. POLARG(1, t = 0, 2*pi, 100) POLARG(1, t = 0, 2*pi, 5) To draw the pentagon inside the circle, reverse the order of the commands and draw the pentagon first. I.4.4 Parametric graphs To graph the parametric functions x = f(t), y = g(t), use the command: PARAMG(f(t), g(t), t = a,b,n) As with polar graphs, you will get n+1 points (f(t), g(t)) connected by line segments for t in the interval [a,b] . Try: WINDOW(-1,1,-1,1) PARAMG(sin(7*t),sin(6*t),t=0,2*pi,200) This is a Lissajous curve. I.4.5 Line Styles and Colors Normally, when you draw several graphs successively without erasing, each is drawn in with a different line style (up to four) or, if you are using an EGA color system, a different color. You can control the line style and color used to draw graphs by executing the command LINESTYLE(n) 0 <= n <= 3 or COLOR(n) 0 <= n <= 15 before graphing. If you prefer to draw graphs with think lines, before drawing the graph enter the command: 20 CC - The Calculus Calculator Oct 27, 1989 THICKNESS(2) To return to thin lines, enter the command: THICKNESS(1) I.4.6 Three-dimensional graphs of surfaces 3 CC can sketch graphs of surfaces in R and then rotate them around all three axes to show how the surface looks from any direction. The surfaces to be graphed can be described either by an equation z = f(x,y) or by three paramtric equations x = f(u,v), y = g(u,v), z = h(u,v). 2 2 To sketch a surface z = x - y , use the command: graph3d(x^2-y^2; x=-1,1; y=-1,1; -1,1; step 10) This will show the portion of the surface in the block: -1 ó x ó 1 -1 ó x ó 1 -1 ó z ó 1 and use 11 values (10 steps) for x and y, or 121 points. The variables x and y must be specified, because they are parameters for the function to be graphed. The variable z need not be mentioned, since it is merely a pseudonym for the function to be graphed. Its name does not appear anywhere in the graphing command. The smallest useful step value is usually 10, and the largest permitted is 30. The time required for graphing is approximately proportional to the square of the step value. Here is another example, the two-dimensional version of the function sin(x)/x. It uses user-defined functions, as introduced in II.8: r(x,y) = sqrt(sqr(x) + sqr(y)) // polar r function g(x,y) = Sin(r(x,y))/r(x,y) // sin(r)/r graph3d(g(x,y); x=-9,9; y=-9,9; -1,1 step 15) CC is also capable of sketching parametrized surfaces. To sketch the parametrized surface: x = r cos(é) y = r sin(é) z = sin(r)/r using parametric values 0 ó é ó 2ã and 0 ó r ó 9, you must also 21 CC - The Calculus Calculator Oct 27, 1989 decide what limits to place on the possible values of x, y and z and how frequently to sample the parameters. We will use the limits -9 ó x ó 9, -9 ó y ó 9, -1 ó z ó 1 and sample the parameters at 16 points (15 steps). All this can be done with the command: paramg3d(r*cos(t),r*sin(t),sin(r)/r; t=0,2*pi; r=0,9; -9,9; -9,9; -1,1 step 15) When you type these long examples into CC, do not press until you have reached the end of the formula. It may not break on your screen exactly as it is divided on the page, but if you keep typing until you reach the end, it will work. Notice that the names x, y and z do not appear in this formula; they are just pseudonyms for the three parametric functions that do appear. However the names of the parameters r and t must be specified. Once a surface appears on the screen, you can change its appearance two ways. You can change its shading from opaque to striped or transparent. To make the figure opaque, press "1" while the figure is on the screen. To make it striped, press "2"; to make it striped the other direction, press "3"; and to make it transparent, press "4" (see Figure xxx). The first surface graphed will initially be opaque, but succeeding surfaces will be shaded identically to the last shading of the prior surface. You can also rotate a surface on the screen. To rotate the surface either way about a vertical axis, press "z" or "Z"; to rotate it about a horizontal axis, press "y" or "Y"; and to rotate it about an axis pointing out of the screen, press "x" or "X" (Figure xxx). If you want to rotate several times, changing the surface to transparent will speed up the rotations. Once the surface is in its final position, change the coloration back to opaque or striped. Here's an interesting surface to try; its equation in 2 cylindrical coordinates is r = 1 + 0.25z . paramg3d((1+0.25*z^2)*cos(t),(1+0.25*z^2)*sin(t), z; t=0,2*pi; z=-1,1; -1.5,1.5; -1.5;1.5; -1,1; 15) Another possibility is the sphere in spherical coordinates: paramg3d(sin(p)*cos(t),sin(p)*sin(t),cos(p); p=0,pi; t=0,2*pi; -1,1; -1,1; -1,1 step 15) 22 CC - The Calculus Calculator Oct 27, 1989 I.4.7 Saving and printing graphs To save any graphics screen in a disk file for later viewing, press Control-F9 while the screen is displayed. You will be prompted for the name of the file for saving the graphics image. Your name may include a path, or you may accept the default name suggested. If you give the name of an existing file, you will be warned that you are about to replace an existing file and asked if you wish to proceed. To recover a saved graph, you must be viewing a text screen, either the Input Window or the Subroutine Window. Press Control- F9 and enter the name of the file holding the graph, and you will see the stored graph on the screen. If you are viewing one graph and wish to see another, you must first exit the current graph by pressing , then recall the second graph as above. If you wish, you may of course save the current graph before leaving it. When a graphics screen is recalled from a disk file, that screen becomes the "Last Graph" when you press to return to the Input Window or the Subroutines Window. The advantage of this convention is that you can begin with a saved graphic and add to it. The danger is that when you recall a graphic, you lose the previous "Last Graph" which was saved from your previous graphic. To retain the previous graphic, recall it by pressing F9 and save it in a disk file before recalling another graphic from disk storage. Files containing 3D-graphics can be transferred between any two computers that will run CC, but files containing 2D-graphics can only be transferred between computers with compatible graphics systems. That means that both computers use one of the systems: CGA or Hercules or EGA or VGA. Files for 3D-graphics are lists of coordinate values that can be interpreted by CC on any computer, but files for 2D-graphics are actual bit-images of the graphics screens and can only be transferred to a screen using the same graphics system. To print a graph, push function key F2 while the graph is visible. Your printer must be capable of printing graphics images compatibly with either Epson or IBM printers. I.5 Lists and arrays CC3 can construct lists of arbitrary length, and the entries in the lists can be of any type of value whatsoever: constants, expressions with undefined variables, or even other lists. Lists are another kind of value in CC3, and they can be assigned to 23 CC - The Calculus Calculator Oct 27, 1989 variables just like simple values. (Since variables in CC3 are untyped, you can assign any value to any variable.) If a variable a is assigned a list value, then in the Output window you will see not just a but the sequence a[1], a[2], ... containing the elements of the list a. If one of these is itself a list, it will be broken up into its components a[1,1], a[1,2], ... . I.5.1 Entering lists To define a list, put its elements between square brackets: a = [1,2,3] b = [f(2), g(1), h(1)] // assumes f,g,h defined c = [[1,2],3,[4,5]] A function can have a list for its value: f(x) = [1,x,x^2] You can define lists another way, with the LIST command: LIST(g(t),t=a to b step c) This is similar to the SUM command. The result is a list: [f(a), f(a+c), ....] which continues until the last value of a + ic <= n . If no step is specified, it is taken to be 1. Try a = LIST(j^2,j=0 to 10) f(x) = LIST(x^j, j = 0,6) b = f(-2) The third way to construct a list is to concatenate two existing lists by writing the symbol | between them. After the sequence of commands just above, try: c = a | b Either a or b or both could be singletons, in which case they would be appended to the beginning or end of the other list. This is how you extend an existing list to include a new element. I.5.2 Accessing lists To find the value of the j'th element in a list a , use the formula a[j] . The first element of a is always a[1] . If the a[j] is itself a list, then its k'th element is either a[j][k] or a[j,k] . Try: 24 CC - The Calculus Calculator Oct 27, 1989 a = [[1,2],3,[4,5]] b = a[1] c = a[1,2] e = a[2] ee = a[2,2] // does not exist An entire sublist of a list a can be accessed with the command a[i:j] , which is the list: [a[i], a[i+1], ... , a[j]] You can even pick out a submatrix with a[i:j,k:l], provided all the entries are defined in a . I.5.3 Modifying lists If the list element a[i] (or a[i,j] etc.) is defined, you can change it with the command: a[i] = ... But you can't use this form unless the i'th element of a is already defined. I.5.4 List operations Lists can be added, subtracted, multiplied, and divided by other lists or by constants. When two lists are combined, they are combined term-by-term, and the combination stops when the shortest list is exhausted. When a scalar is combined with a list, it is combined with each element of the list. Try: a = [1,2,3] b = [4,5,6] a + b a / b 3 * a b - 4 If f(x) is a built-in function and a is a list, then f(a) results in a list of the values f(a[i]) . Try to continue the series just above with: sqrt(a) You can sum or multiply all the elements in a list a with the commands: SUM(a) PROD(a) 25 CC - The Calculus Calculator Oct 27, 1989 You can find the number of elements in a list, and their maximum and minimum with the commands: LENGTH(a) MAX(a) MIN(a) If you use a list as the value of a variable in a user-defined function, CC3 will try to use the list in the calculation. For example: F(x) = SUM(Sqr(x)) F([1,2,3]) This functions takes the sum of the squares of the elements of the list x. I.5.4.1 Vector operations You can use lists as vectors, adding them and multiplying them by scalars. For example, the dot product of two vectors is: dot = SUM(a*b) You can even make this into a function: Dot(x,y) = SUM(x*y) a = [2,3,5] b = [4,3,2] Dot(a,b) How about the cross product: Cross(a,b) = [a[2]*b[3]-b[2]*a[3],a[3]*b[1]- b[3]*a[1],a[1]*b[2]-b[1]*a[2]] I.5.4.2 Lists and statistics If a is a list, you can find the average and standard deviation of the entries in a with the commands: AVERAGE(a) STANDEV(a) To perform a linear regression, use the command: r = REGR(a,b) where a and b are lists. The regression is through the points (a[1],b[1]),...,(a[n],b[n]). The output of REGR is a list with three elements: r[1] is the slope of the regression line, r[2] is its y-intercept, and r[3] is the 26 CC - The Calculus Calculator Oct 27, 1989 2 regression coefficient (NOT r ). To display a histogram of the elements in a list, use: HISTOGRAM(a,r,s,n) CC3 divides the interval [a,b] into n subdivisions and shows the histogram of the elements of a according to these subdivisions. Outliers below r or above s are included in the bottom and top categories respectively. If a is a list of integers in the range 1..n, you can make a histogram of a with the command: HISTOGRAM(a,1,n,n) Here's a sequence of commands that illustrates the statistical commands: f() = Random + Random + random + random + random // approximate normal random variable // mean 2.5, variance 5/12 // x is not used in definition, can be anything a =list(f(), j=1,100) // 100 random numbers AVERAGE(a) STANDEV(a) a = List(j,j=0,1.05,0.1) b = list(j+f()/5, j=0,1.05,0.1) r = REGR(a,b) r[1] // slope of regression line r[3] // correlation coefficient In the last example, we are finding the regression line through the points (a[j], b[j]), a[j] = (j-1)/10 and b[j] is approximately equal to a[j]. The regression line should have slope approximately equal to 1. I.5.4.3 Graphing lists If a and b are two lists, we can connect the sequence of points (a[i], b[i]) with line segments by using the command LISTG(a,b) First construct a window WINDOW(0,1,-1,2) then execute LISTG on the lists a and b constructed just above. To add the regression line through the points, use the command: SKETCH(r[1]*x+r[2],x) 27 CC - The Calculus Calculator Oct 27, 1989 I.5.4.4 Viewing and Printing lists Lists can be viewed with the TABLE command. To view the list X[1]..X[N], use the command TABLE(X[J],J=1 TO N, N-1) Printing a list is even easier. To print the list X, just turn on the printing feature by pressing function key F2 and enter the command: X = X I.6 Odds and ends of Calculator usage I.6.1 Using Help Effectively You can access the CC manual online by pushed function key F2. Once the file is visible, you can scroll through it using the keys up-arrow, down-arrow, PgUp, PgDn, Home and End. You can also search for a particular topic or section number by typing the string you wish to search for and pressing . To repeat your search for the next instance of the string, just press Control-L. All searches proceed forward from the current position in the file. I.6.2 Using the printer Push function key F2 and all your entries to the Calculators as well as all your calculated results will be printed. Push F2 again to turn the printer off. While printing is enabled, you will be queried if you want to print each graph you display. See I.4.7 for more information on printing graphs. 28 CC - The Calculus Calculator Oct 27, 1989 I.6.3 Saving and loading work from disk Anytime you want, you can save all of your existing Calculator lines and Scratchpad entries to a disk file. Just push function key F7 and enter a file name when prompted. To read this information back into the Calculator, push function key F8 and enter the correct file name at the prompt. When you load information from the disk, it is appended to whatever lines are already in the Calculator, so nothing is lost. The lines that are read in are not executed (although they are compiled). The Scratchpad functions are procedures are ready to use, but any function or variable definitions read into the Calculator must be executed before they are effective. I.6.4 Controlling output precision CC3 normally prints its results with 10 digits precision. You can change this with the command: PRECISION(n) where n is the number of digits precision you wish to display. Internally, all values are stored at full precision no matter what output precision you specify. I.6.5 Controlling precision of Integration and solving operations The operation SOLVE(f(x),x=a) converges when x is found such that: |f(x)| < max(|x|,1)SolveTolerance where SolveTolerance is a constant in CC3. The default value of SolveTolerance is 0.0000001; you can change it to any value v you like with the command: SOLVETOL(v) This factor also controls the convergence of the IMPLICIT operator. The operation IN(f(x),x=a,b) first divides the interval (a,b) into three subintervals, and computes the midpoint of each. Based on these three subintervals, a midpoint approximation M and trapazoidal approximation T are computed for the integral. If T and M are approximately equal, then Simpson's approximation (2*M + T)/3 is returned as the value of the integral, otherwise the process is repeated on each of the six subintervals of (a,b) that have been constructed. There are constants IntegrationTolerance and IntegrationDepth controlling this process. Integration on an interval converges if (b-a)*IntegrationTolerance > |T - M|; 29 CC - The Calculus Calculator Oct 27, 1989 the application of the algorithm to repeated subdivisions of the original interval will continue up to a depth of IntegrationDepth. That is, the maximum number of subintervals that can be constructed during integration is IntegrationDepth 6 . The initial values are IntegrationTolerance = 0.0001 and IntegrationDepth = 5; these can be altered with the commands: INTOL(v) // new value for IntegrationTolerance INDEPTH(n) // new value for IntegrationDepth When FIN (Fast INtegration) is performed, we temporarily set IntegrationTolerance = 0.1 and IntegrationDepth = 2. I.6.6 Monitoring memory usage When CC3 starts, it measures available memory. The program halts immediately if insufficient memory is available. If only a small amount of memory is available for running CC3, the program warns the user. The number that appears in the lower-right corner of the screen is the number of free bytes remaining in your computer's memory while the calculator is running. On my 640K AT clone with Hercules-style graphics, I start out with about 200,000 free bytes. This number changes dynamically while the calculator is calculating, so you can see how much memory is necessary for different calculator operations. Normally while CC3 is running a large amount of memory is devoted to saving the last graphics screen (30,000 bytes for Hercules graphics; 64,000 bytes for EGA graphics; 150,000 bytes for VGA graphics). This is used for the graphics saving feature; when you press function key F9, you see the last graphics screen drawn. You can direct CC to save the last graphics screen on disk instead of to memory by pressing Shift-F9. When you do this, the number at the lower-left corner of the calculator screen indicating available memory will increase. If for some reason (e.g. there is no disk in the disk drive) CC cannot create a file to hold the graphics image, it will warn you and the graphics save feature will be disabled. Pressing Shift-F9 again will switch the graphics saving feature back to memory(if there is enough memory to enable it) and remove the necessary memory block from the heap. The available memory will decrease accordingly. If insufficient memory exists to hold the graphics screen, CC will recreate the disk file for holding graphics images on disk. Thus, if you tried to switch to 30 CC - The Calculus Calculator Oct 27, 1989 saving graphics and disk and failed, fix the disk problem and try again. Related features are discussed in section I.4.7 under the heading "Saving and Printing graphs." CC3 constantly monitors its available memory, and it stops with an error message if insufficient memory is available to complete an operation. To make more memory available, you should FORGET unnecessary variables and erase unnecessary lines from the Calculator and ScratchPad. You could also move the last grpah buffer from memory to disk. On a more technical note, here is how CC3 monitors memory. Frequently during calculations it measures the amount of free space in the heap and the stack, and if one of these appears dangerously low then it stops with an error message. Thus it is possible but unlikely that CC3 will crash with an out-of-memory error. 31 CC - The Calculus Calculator Oct 27, 1989 II. Programming CC3 CC3 is designed to be a programming environment optimized for numerical algorithms. It is easy to program and test numerical algorithms in CC3. The programming language is designed to be a simplified version of Pascal, but you may note features borrowed from C and Basic. A note about variables. They are entirely untyped, but totally local. No variable from one procedure or function can be referred to directly by another; not even global variables from the Calculator are available to Scratchpad functions. To share information between operations, you must use the explicit parameter-passing mechanisms provided. II.1 How to use the Scratchpad Push function key F10. You should see a new screen, called the Scratchpad. On the Scratchpad you can write multi-line procedures and functions that can be invoked from the Calculator. These operations can invoke each other too. As you type on the Scratchpad, you will notice one important difference from the Calculator. When you push , the line you are working on divides at the cursor, and lower lines are pushed down. This is different from the Calculator, where pushing executes a line but does not change it. Lines in the Scratchpad are never executed until the procedure or function they belong to is executed, but the lines are compiled as soon as you leave them. If you enter an incorrect line, a warning message is flashed on the screen. At any time your Scratchpad can be saved with your Calculator on disk (I.6.2). You can add previously saved Scratchpad routines to your current Scratchpad by loading them from disk (I.6.2). II.2 Procedures and functions There are two types of Scratchpad operations: Procedures and Functions. Each is a sequence of lines that is executed just like lines in the Calculator, but Functions return a value while Procedures do not. Here are two easy examples. Type them into your Scratchpad: 32 CC - The Calculus Calculator Oct 27, 1989 Procedure First // my first procedure Write('Hello') end Function One // my first function Return(5) end Now push F10 to switch back to the Calculator, and enter the commands: First a = One First caused the message "Hello" to be flashed on the screen; One returned the value 5. Notice that the last line of every procedure or function must be the single word: END To return a value from a function, use the command; RETURN(v) The value of a function is the last value RETURNed; it is undefined if no value was returned. You can use parameters in your Scratchpad procedures and functions just like variables in functions in the Calculator. Here are some more examples: Procedure Regression(n) // produce n points and display them and // regression line through them Window(0,1,-1,2) a = list(j/(n+1),j=1,n) // points on x-axis in interval (0,1) b = list(a[j]+random/3,j=1,n) // b[i] is approximately a[i] with random error Listg(a,b) r = Regr(a,b) sketch(r[1]*x+r[2],x) end Function uniform(n) // returns number of heads out of n coins // useful for statistical modeling a = list(random(1),j=1,n) // n 0's and 1's return(sum(a)) // number of 1's end 33 CC - The Calculus Calculator Oct 27, 1989 II.2.1 Functions as parameters CC3 permits function names to serve as procedure or function parameters, so you can write a procedure that applies to an arbitrary function. Simply put the sign % in front of the parameter name if you want it to refer to a function instead of a value. Of course, you must match the parameter up to function of the right number of variables (the number that the procedure expects to find in the function) when you call the procedure. Here's an example: Function Der(%f,a,eps) // approximate the derivative of f(x) at a dd = (f(a+eps/2) - f(a-eps/2))/eps return(dd) end Note that the function name f was not preceded by % in the body of the procedure. To call the procedure from the Calculator, use something like: g(x) = sin(x^2) Der(g,sqrt(PI),0.001) A function parameter must be matched to a user-defined function defined on the Calculator. It cannot be matched to another Scratchpad function or a built-in function. You could not say Der(sin,PI,0.001) . II.3 Program flow control CC3's programming language includes complete facilities for logical programming. While these notes are not intended to each you to program, we will illustrate how CC3 uses IF..THEN..ELSE , WHILE..END, REPEAT..UNTIL, and FOR..END. CC3 includes a special emergency escape command: EXIT Anytime you execute this command, you will leave the current function or procedure no matter how deeply imbedded you are in control structures. II.3.1 Comparison operators Before you can write loops, you must be able to write statements that evaluate to TRUE and FALSE, and before you can do that you must be able to write useful statements with logical values. In mathematics, these are comparison statements. CC3 allows you to compare numbers six ways: 34 CC - The Calculus Calculator Oct 27, 1989 a < b less than a <= b less than or equal to a > b greater than a >= b greater than or equal to a == b equal to NOTE THE DOUBLE == a <> b not equals CC3 uses the double equals sign == (like C) for "is equal to" to distinguish this operator from the assignment operator. The reason for this departure from Pascal is to make it easier for non-programmers to write variable and function definitions without struggling with := . (Actually CC3 will recognize := as equivalent to =, and it doesn't mind if you put semicolons at the ends of statements or append THEN to IF and DO to WHILE or FOR. It just doesn't need these things.) The result of a comparison is one of the values TRUE or FALSE or UNDEFINED. Remember that these are all values which the user can enter into CC3 too. Complex numbers and UNDEFINED can be meaningfully compared with == and <>, but the ordering comparisons always return UNDEFINED when applied to complex or undefined values. In advanced programming applications, it may be necessary to identify whether or not a value is a list. You can do this with the command ISALIST as follows: ISALIST(a) returns TRUE if a evaluates to a list and false otherwise. II.3.2 Logical operators CC3 uses the logical operators: AND, OR, and NOT. You can combine comparison operators with them to any level of complexity . In contrast to Pascal, logical operators in CC3 have a lower order or precedence than the comparisons, so a < b and c > d works as expected. The result of combining logical values with logical operators is another logical value. Bit operations on integers can be performed using the same operations, but integers and logical values cannot be mixed. In other words, 3 AND TRUE results in UNDEFINED. 35 CC - The Calculus Calculator Oct 27, 1989 CC3 uses the "short-circuit" definition of AND and OR when the arguments are boolean or undefined. Here are tables that show how AND and OR are defined: a AND b b True False Undefined a True True False Undefined False False False False Undefined Undefined Undefined Undefined a OR b b True False Undefined a True True True True False True False Undefined Undefined Undefined Undefined Undefined Short-circuit evaluation is used because often one condition must be tested before another is meaningful. Typical is a line like: IF IsAList(x) and (x[1] == 0) If x is not a list, then we want this condition to return False, not Undefined or erroneous, so we want the falsity of the first condition to make the entire expression false and even to stop evaluation of the second term. II.3.3 Conditional statements When programming in CC3, you can use the format below to construct a series of choices. IF .... .... ELSE IF ... ... ELSE IF ... ... ELSE ... END Note that each line IF... and ELSE IF ... and ELSE and END must occupy their own line of the program. You cannot write IF a < b THEN x = 3 . You must write: IF a < b x = 3 END 36 CC - The Calculus Calculator Oct 27, 1989 As an example of the use of the IF alternation, we will construct the function Sign(x), which returns 1 if x > 0, -1 if x < 0, and 0 if x = 0: Function Sign(x) // returns -1 if x < 0, 1 if x > 0, 0 if x = 0 IF x < 0 return(-1) ELSE IF x > 0 return(1) ELSE return(0) END // If clause END // of function II.3.4 Loops You can use two kinds of loops in CC3, fixed length loops controlled by FOR and variable-length loops controlled by WHILE and REPEAT. These are similar to the same constructs in Pascal, with the differences that: DO is never required (but permitted) after FOR and WHILE WHILE, FOR, REPEAT, UNTIL, END must be on their own lines BEGIN is not required or permitted END is required to terminate FOR and WHILE, even for one-line loops The control variable in for loops is not limited to integer values. As in Basic, you can say: FOR x = a TO b STEP dx 37 CC - The Calculus Calculator Oct 27, 1989 where a, b, and dx are real values. If STEP is omitted, it defaults to 1. Here are two routines that use FOR loops: Function Sort(a) // a is a list. returns a sorted copy // of a FOR j = 1 to length(a)-1 // put largest element in a[j..] into a[j] FOR k = j+1 to length(a) IF a[j] > a[k] x = a[j] a[j] = a[k] a[k] = x END // IF END // FOR k END // FOR j RETURN(a) END // Sort Note that invoking this procedure from the Calculator with the command: y = Sort(x) the variable x is unaffected. To sort a list itself, use x = Sort(x) Here's another example, this time one that computes the midpoint approximation to the integral of an arbitrary function f(x) (cf. II.2.1). Function Mid(%f,a,b,n) // compute the midpoint approximation to the // integral of f(x) on the interval [a,b] // using n intervals dx = (b-a)/n M = 0; FOR x = a+dx/2 TO b STEP dx M = M + F(x) END RETURN(M*dx) END // Mid The conditional loops are probably more useful than FOR loops, so CC3 includes both WHILE and REPEAT loops. Here is a sample program using the WHILE loop. 38 CC - The Calculus Calculator Oct 27, 1989 Function Wait(p) // assume an event has probability p of // occurring in each time interval beginning // with time interval 0. Return number of // time intervals until event takes place. // This function may return a different value // each time it is executed. It models a // Poisson process. n = 0 WHILE Random > p // if event fails n = n+1 END RETURN(n) END // Wait Here is a program that uses a REPEAT loop: Procedure Chase(n) // n creatures start on the circumference // of a circle and chase each other to the // center. window(-1.4,1.4,-1,1) graphics PolarG(1,t=0,2*pi,200) // draw a circle x = list(cos(2*pi*j/n),j=1,n); y = list(sin(2*pi*j/n),j=1,n); // x,y are lists of starting x,y-coordinates // for creatures REPEAT d1 = sqrt(sqr(x[1]-x[2])+sqr(y[1]-y[2])) // distance between creatures a = x[n] b = y[n] For j = 1 to n do // move creature(j) towards (a,b) c = x[j] // old position(j) e = y[j] f = c + (a-c)/d1*0.03 // new position(j) g = e + (b-e)/d1*0.03 line(c,e,a,b) x[j] = f // update x,y y[j] = g a = c b = e end UNTIL d1 < 0.03 text end The variables a,b,c,e,f,g are not strictly necessary. They could be replaced by repeated references to x[j], y[j], etc., but they speed up the algorithm. CC3 uses linked lists to store 39 CC - The Calculus Calculator Oct 27, 1989 lists, which is why you can uses lists without first dimensioning them. But the drawback to this method is the slowness with which list elements are accessed. Each time you refer to x[j], the entire list x up the j'th element must be traversed. Thus it pays to use auxiliary variables as in the procedure above in place of repeated references to list entries. II.4 Special programming operations CC3 includes some special facilities for adding interactive and graphical features to your programs. Like the control statements, these cannot be used in the Calculator but only in the Scratchpad. II.4.1 Writing output To put a message on the screen and hold it until the user presses a key, use the command: WRITE(a,b,c,..) The entries a, b, ... can be numerically (or list or boolean) valued expressions, or they can be strings enclosed in single quotes. They must be separated by commas. For example: WRITE('The first result is',x^2-2) II.4.2 Obtaining user input CC3 enables you to get input from a user while a program is running. You are limited to a single numerical value, but the numerical value can be entered as a formula, not just a number. To get input, use the command: INPUT('message',variable) If you use INPUT, a numerical expression is expected and its value is placed in the variable. The message can be omitted, and CC3 will substitute a generic message. For example: INPUT('Enter lower value',x) User could respond 3 or sin(5) or 2/3, etc. Any legitimate CC3 formula using only constants and built-in functions is valid, but strange things may happen if the user tries to include a variable name or user-defined function name in the response to INPUT. 40 CC - The Calculus Calculator Oct 27, 1989 II.4.3 Strings Alphanumeric strings are legitimate values for the variables in CC3. You assign these values with commands like: a = 'abc' using apostrophes to delimit the string. This works in both the Scratchpad and the Calculator. Try it in the Calculator. String values can be compared with all the comparison operators, and the comparisons are case-sensitive. The most frequent use of string values is as user-input to a procedure or function. To stop your program so the user can enter a string, use the command: INPUTS('message',variable) This is just like the INPUT command, but the variable is assigned whatever string the user types. The input is not evaluated. You might use INPUTS like this: REPEAT ... INPUTS('Do you want to continue (Y/N)?',yn) until yn = 'n' or yn = 'N' II.4.4 Graphics programming All the graphics commands in CC3 can be included in Scratchpad routines, but sometimes it is useful to use several lines to build a picture. You can freeze the compute in graphics mode with the command: GRAPHICS Then any graphics commands will just add to the screen, but the program will not pause at the end of each one. You turn off graphics mode with the command: TEXT When this command is issued, the computer pauses, shows the crosshairs, and waits for the user to push . Sometimes you will want to pause while drawing a picture on the graphics screen, for example you might want to pause after each step of some graphical approximation procedure. While in Graphics mode you can cause the computer to pause between commands and wait for the user to push by issuing the command PAUSE 41 CC - The Calculus Calculator Oct 27, 1989 While in graphics mode you can erase the screen with ERASE or erase and resize the graphics window with WINDOW. You can also plot individual points on the graphics screen (using coordinates relative to the current window) with the command: PLOT(x,y) You can also draw a line from (a,b) to (c,d) with the command: LINE(a,b,c,d) PLOT and LINE can only be executed after the command GRAPHICS has been executed (in real time) and before TEXT is executed. For some graphics operations, it is necessary to determine the current boundaries of the graphics window. For example, you might wish to stop drawing a level curve when it ran out of the window. There are four functions that return the window boundaries: WINDOWLEFT WINDOWRIGHT WINDOWTOP WINDOWBOTTOM For example, the following one-line function returns TRUE if the point (x,y) is in the current window, otherwise it returns FALSE: OnScreen(x,y) = x >= WINDOWLEFT and x <= WINDOWRIGHT and y >= WINDOWBOTTOM and y <= WINDOWTOP As our final example, we will show how to trace the iterates of the function f(x) = rx(1-x) on the graph of this function. The user must specify the parameter r and the number of iterates to be produced. Procedure Iterate(r,n) f(x) = r*x*(1-x) Window(0,1,0,1) GRAPHICS QuickG(f(x),x) Sketch(x,x) // 45-degree line x = 0.5 FOR j = 1 TO n y = f(x) LINE(x,x,x,y); LINE(x,y,y,y) PAUSE x = y END // FOR j TEXT END // Iterate 42 CC - The Calculus Calculator Oct 27, 1989 Try this program with r = 0.7, 1.8, 2.9, 3.2, 3.5, 3.56, 3.8. Then read Devaney, One Dimensional Dynamical Systems. II.4.5 Sound If you want to call the user's attention to something, you can make the computer emit a short sound with the command BEEP BEEP must appear on its own line. 43 CC - The Calculus Calculator Oct 27, 1989 III. Recursive Definitions in CC3 CC3 has three kinds of definitions: 1. procedure and function definitions in the Scratchpad 2. variable assignments 3. single-line function definitions I will discuss recursion for each type separately. To understand how recursion works in CC3, you must also understand at what point in the calculator's operation values are bound to expressions. III.1 Scratchpad Procedures and Functions Procedure and function definitions in the Scratchpad are the easiest to understand. These are stored as lists of lines just as you enter them. The individual lines are compiled as they are entered (so sometimes an error message will flash on the screen if you enter an erroneous line into the Scratchpad), and the procedures are interpreted line by line when they are called from the Calculator or by another Scratchpad procedure. Since each invocation of a Scratchpad procedure or function has its own set of local variables, they can call themselves recursively either directly or indirectly. This is the sort of recursion which is familiar to users of Pascal or C. CC3 monitors its own heap (I.6.5), and it will not crash on infinite recursion. To see the error message generated by recursion calls that go too deep, and to find out how deeply recursion calls can go on your computer, enter the following procedure into the Scratchpad and invoke it from the Calculator with the command R(1) : Procedure R(n) Write('Recursion depth',n) R(n+1) end My computer, with 640K and Hercules-style video, achieves a depth of 31 before quitting. III.2 Variables Variables are assigned values when their definitions are executed. Thus, if you define a variable: b = a+2 b is given a value depending the value of a when the definition is executed. If a is later given a different value, the value of b will not change. 44 CC - The Calculus Calculator Oct 27, 1989 You can also enter the recursive command: a = a+2 which results in replacing the old value of a by a new value. Note that if b was undefined at the time the first line was executed, then a would have for its value the algebraic expression b+2 . If you then executed the second line, then the new value of a would be b+4 . III.3 Single-line function definitions When you define a function, for example: g(x) = sin(x+a) the expression on the right is stored in the computer's memory. In particular, the constant a is stored as a literal constant; it is not evaluated when g(x) is defined. When you later evaluate the function g(x) by entering g(2) , for example, the value you get depends on the value of a at the time you perform the evaluation. Because no component of a function is evaluated until the function is invoked, it is not possible to use the sequence of commands: g(x) = sin(x) g(x) = d(g(x),x) This is the exact opposite of the situation with variables. With functions, the second definition simply replaces the first, and your first invocation of g(x) , for example attempting to compute g(Pi) , will result in infinite recursion. Try it. Nevertheless, it is occasionally useful to define a sequence of functions in terms of the previous entries in the sequence (i.e. recursively). To do this, use the command EVAL . The expression EVAL(...) automatically replaces all defined terms in (...) with their definition, even if the expression appears to the right of a function definition. Thus if you entered: g(x) = Sin(x) g(x) = EVAL(d(g(x),x)) the definition of g(x) would be Cos(x) . The EVAL command is particularly useful for taking repeated derivatives of a function. You can define the following operator in the Scratchpad: 45 CC - The Calculus Calculator Oct 27, 1989 Function DiffN(%f,n,a) // returns the value of the n'th derivative // of f(x) at x = a for i := 1 to n do f(x) = eval(d(f(x),x)) end return(f(a)) end When you apply EVAL(....) to an expression, two kinds of components are not replaced by their definitions: calls to RANDOM and calls to Scratchpad procedures. You would not want to replace calls to RANDOM with fixed random values when you used EVAL to define a function, and it is not possible to replace a call to a Scratchpad procedure with the entire procedure inside a one-line user-defined function. 46