You are on page 1of 15
APPENDIX | Computers and Electromagnetic Theory In the course of the last fifty years, the digital computer has evolved from a rare item to one that is commonly available, not only in research establishments, but also to any individual who has a need for one. Science and engineering, as well as many other human activities, have been major beneficiaries of this increased availability. Very few electricity and magnet- ism texts, however, say anything about computers. As a result the transition from the neat problems that are treated analytically to the messy problems that occur in applications is abrupt if not traumatic. The objective of the computer material in this book is to ease the discontinuity and facilitate the use of computers in exploiting electromagnetic theory. The two important ingredients, in addition to electromagnetic theory, are numerical analysis and computer programming. However, while this appendix is relatively self-sufficient, it is not a text on numerical analysis, or computer program- ming, or the BASIC language. The bibliography at the end of this appendix contains a selection of material on each of these topics. THE EVOLUTION OF COMPUTING Computation has had a long history, but its most dramatic development phase began after World War II. Before 1940, the computers used by most physicists were arcane, hand-powered devices that required some skill to operate. During World War II a small number of large-scale (by 1940 standards) electronic digital computers were built, mainly to satisfy the needs of ballistics and cryptography. By the early 1950s, new general- purpose computers were beginning to appear, and one such device, WHIRLWIND, gained a place of honor in the Smithsonian Institution at the ripe old age of thirty. By the late fifties, standard, large electronic computers had become available from several vendors. These systems were 879 Appendix I bulky and used vacuum tubes to implement the hardware requirements. But the astonishing development of semiconductor devices led to smaller computers and greater capacity (and incidentally lower cost computing). These trends continued, leading to mini-computers in the 1970s and micro-computers by the end of that decade. The introduciton of the PC by IBM in mid-1981 was an important event because it led to a standardization of architecture and operating systems and so to the development of third-party software. At the present time, commercially available computers span the range from giant supercomputers to very capable pocket-sized micro-computers. Desktop computers, in particular, are capable of im- plementing important applications in electromagnetic theory and are very affordable. The fact that computers must be told what to do requires a computer language. In the early days of computers, each one had its own language, typically built from very simple instructions that were used in enormous arrays. Learning a new language was painful and slow, and so impeded the adoption of new computers. In the late 1950s, this problem was solved with the invention of a standard language called FORTRAN (FORmula TRANSslator) by John Backus and co-workers at IBM. Using FORTRAN made it possible to instruct the computer (write programs) in a language similar to ordinary English. This language was not understood by the computer, but it could be translated into machine language in a process now called compiling. Since compilers can be changed to adapt to new machine languages without affecting the language used by the programmer, early programmers could use FORTRAN to program any machine that was equipped with a FORTRAN compiler without learning a complex new language. FORTRAN remains a very popular high-level language among scientists and engineers. It has been standardized by the American National Standards Institute, and the current version is FORTRAN 77 (ANSI X3.9-1978). A revision, FORTRAN 90, should be available soon. FORTRAN required too much memory to be useful on early micro- computers. Thus, another language, called BASIC (Beginners All-purpose Symbolic Instruction Code), was developed by John Kemeny and Thomas Kurtz to solve this problem and simplify the programming process. The BASIC language is also closely related to English and in many ways is similar to that of FORTRAN. The two most apparent differences are that standard BASIC identifies each instruction line with a number, and each line is converted to machine language and executed sequentially in a procedure called interpreting. Compiling, as is done with FORTRAN, converts the entire program and optimizes the machine language version before executing the program. BASIC was so useful that it was and still is supplied with most desktop computers. It too has evolved, with the most recent standard versions being BASIC 3.22 and 3.33. In 1990 a new version of BASIC called QBASIC appeared. It is incorporated into DOS 5.0, and currently it is being shipped with many desktop computers that use DOS. Computers and Electromagnetic Theory 581 QBASIC does not use line numbers and has several other advantages, but it is still interpreted. More advanced versions of BASIC avoid the line numbers and also compile rather than interpret. Other languages have been developed that have significant advantages for some purposes, but BASIC and FORTRAN are still the languages most commonly used by scientists and engineers. What Computers Do ‘A computer system, regardless of size, typically consists of four units: input, output, central processor, and memory. The first two provide for com- munication with the computer and consist of keyboards, tape and disk drives, video screens, printers, plotters, and so on. The memory provides for the storage of data and instructions within the computer where they can be accessed readily as needed. It usually consists of two independent parts: the random access memory (RAM), which is used for storage while the central processor is carrying out its assignments, and disk or tape storage, which is used for long-term storage. There are also relatively small read-only memories (ROM), which are used to store frequently used material BASIC, for example, is sometimes contained in ROM. The central processor unit (CPU) can do elementary arithmetic and logical operations in response to instructions provided by its controller. The controller in turn provides communication with the rest of the computer and conversion of instructions to a form suitable for use by the arithmetic and logical elements of the CPU. The basic functions may be thought of as communications, storage, arithmetical operations, and logical operations. From these basic functions, sequences that accomplish very complicated tasks can be constructed. For the purposes of electromagnetic theory and mathematical physics in general, these capabilities translate into the ability to carry out complex computational instructions containing both arithmetic and logical elements, the ability to repeat calculations for different values of arguments or parameters, and the ability to do symbolic mathematics. APPLICATIONS OF COMPUTERS TO ELECTROMAGNETIC THEORY The computational capability facilitates many useful tasks, and we now illustrate a few with references to the main text where they are used. One of the most frequently used capabilities is the repeated evaluation of mathe- matical expressions. In Chapter 13, the transfer function of a simple network is obtained as an algebraic expression. A simple computer program evaluates this expression over a specified range of frequencies with a specified step size. Doing this evaluation manually for a single frequency is Appendix not difficult, but for 100 different frequencies, the computer provides definite advantages. In Chapter 3, Laplace’s equation is solved for a rectangular region using a series expansion in sines and hyperbolic sines. A computer program is used to evaluate the potential at specified points. This program takes advantage of the pre-programmed ability of BASIC to compute sines and exponentials. Here again the computation is not intrinsically complex, but summing 11 terms of the series for even one specific point is laborious. Also in Chapter 3, a set of finite difference equations is solved by an iterative technique. Each individual calculation is simple, but it must be repeated 50 times per iteration, and it may take 50 or more iterations to obtain a sufficiently accurate result. The computer does these calculations very rapidly. In Appendix VII, integrals are evaluated numerically in order to use the dispersion relations. This automation of a formerly laborious manual task is extremely important in science and engineering. In addition, circuits, boundary value problems, and many other applications involve the solution of sets of simultaneous linear equations. This process is sufficiently common that we consider it later in a separate section of this appendix. Chapters 3 and 13 contain examples requiring the solution of simultaneous linear equations. Approach Our approach to computing in connection with electromagnetic theory is epitomized by the imperative statement, “Use clever software written by other people.” There is so much software now available that this valuable advice must be tempered with the observation that it is sometimes quicker to modify a good program that does almost what is needed than it is to locate a program that does exactly what is needed. The appropriate balance is a matter of taste and develops with experience. We make no claim of elegance for the listed programs. They are as simple and direct as we could make them while still serving the required purposes. To the best of our knowledge, none of the programs in the text appear elsewhere in the form we have used. Many of them, however, owe debts to long lists of people who have written and modified similar programs. For each application in the text, we have tried to present several approaches of varying generality and varying sophistication. Where known to us and readily available to others, we have also cited more general and more sophisticated program listings. Finally, with the same caveats, we mention some commercially available software. Since commercial software changes rapidly we have not tried to be either complete or current, but only to give the flavor of what is available. ‘The problems require modification of programs listed in the text or, in some cases, the writing of new programs. They usually extend the text and often provide for more detailed exploration of idealized examples. Computers and Electromagnetic Theory 583 Specific Hardware and Software ‘The baseline hardware system for the material in the text is an IBM PC-XT, with two 360-K floppy drives, 640-K RAM, a graphics card, and an appropriate monitor (or any of the numerous clones of such a system). A printer, even of the inexpensive nine-pin dot matrix variety, is useful but probably not essential, except for submitting exercises. The essential software is a disk operating system, MS DOS version 2.11 or higher, and a compatible version of BASIC. Version 2.02 will work with DOS 2.11 or higher, but BASIC version 3.22 requires DOS version 3.2 or later. Alternatively, a Macintosh and an appropriate version of BASIC can be used, but this may require some modification of the programs listed in the text. A hard drive will save a great deal of time and represents a useful enhancement. In the realm of software for scientific and engineering applications, a graph plotting program is extremely useful;* but unfortun- ately, most inexpensive packages do not produce graphs of suitable quality for science and engineering use. Packages that produce good graphs tend to be expensive and often require a hard drive. A useful alternative is provided by BASIC routines that produce at least rough graphs. One such routine is listed by Miller.+ We decided to use standard BASIC (by standard BASIC we mean any of the versions using line numbers) to present programs in the text. The main reasons for this choice are simplicity, availability, adaptability to a variety of host computers, availability of compilers, and similarity to FORTRAN. BASIC programs will run on QBASIC, where the line numbers are optional, but the converse is subject to significant restrictions. The availability of compilers deserves comment. Because BASIC is inter- preted, it executes relatively slowly, but compiled versions of BASIC have been developed that provide faster execution. These typically suppress the line numbers characteristic of ordinary BASIC and make some changes in the language, which generally make it even more like FORTRAN. The compiled versions of BASIC run faster but are not really needed for the problems in the text. One point that is often obscure is that programs written in ordinary BASIC or QBASIC (e.g., the programs in this text) can be compiled. To accomplish the compilation, the complete BASIC pro- gram, including all subroutines, is saved as an ASCII file (the SAVE “filename”,A command in BASIC; automatic in QBASIC). This file is then loaded into the compiler, and the compile routine is executed. Alterna- tively, the program including the essential line numbers and all subroutines * Some of the graphs in the text were produced using Tech + Graph» Pad (Copyright Binary Engineering Software, Inc.), which is a typical commercial program capable of producing publication-quality scientific and engineering graphs. + See the bibliography listed at the end of this appendix 584 Appendix I can be typed directly into QuickBASIC. The compiled program will usually run several times faster than the original, depending on the program and the compiler. QuickBASIC (Microsoft Corporation) almost always gives a substantial (three- or four-fold) improvement. Some other compilers do not perform as well. BASIC also has some disadvantages. The two that we note are that, first, the language does not deal with complex numbers as a standard type of numerical quantity. As a result, equations involving complex numbers must be explicitly decomposed into real and imaginary parts. This process is particularly annoying in dealing with ac circuits and wave propagation. The second disadvantage is that there seems to be no readily available, extensive compilation of useful scientific and engineering programs in BASIC. Books by Miller* and Walker* are useful, but for general utility they do not compare with Numerical Recipes,* which is now available for FORTRAN, PASCAL, and C. For QuickBASIC, the situation has improved with the appearance of Numerical Recipes in BASIC, which is a supplement to Numerical Recipes. The routines in this supplement run on QuickBASIC 4.5 and can often be adapted easily to QBASIC. Adapting them to BASIC is not something we recommend. BASIC has other shortcomings, but at this level they are clearly outweighed by the advantages. Hardware and Software Summary Hardware: Desktop computer using DOS operating system with at least two 360-K floppy drives Graphics card Monitor Software: DOS operating system BASIC, QBASIC, or QuickBASIC compatible with DOS version It is almost impossible to buy BASIC alone. It is, however, usually supplied with DOS and packaged with IBM PC’s and clones. QBASIC is packaged with DOS 5.0, and alternatively the disks are supplied with Learn BASIC Now by Halvorson and Rygmyr,* where it is called “Interpreted QuickBASIC.” QuickBASIC, cur- rently Version 4.5, is readily available at computer stores. QBASIC and QuickBASIC are substantial improvements on BASIC because they include additional statements and because they are more convenient to use. If you are new to BASIC, we would recommend starting with QBASIC rather than BASIC. The programs and code in this book will run without change in almost any version of BASIC, QBASIC, or QuickBASIC. Line * Sce the bibliography listed at the end of this appendix. Computers and Electromagnetic Theory 585 numbers are required in BASIC and are optional in the other two. The limitations of BASIC, however, require that the programs be written in such a way that some line numbers are essential. These essential line numbers are indicated in the heading box for each program. If the program is being typed into QBASIC or QuickBASIC, only the essential line numbers need be entered. If a program is typed in BASIC (including line numbers), it can be used in QBASIC or QuickBASIC by saving it using SAVE “MYPROG.BAS”,A and then opening it in the prescribed way in the other software. Programs originated in QBASIC or QuickBASIC with line numbers (note that line numbers are not entered automatically) will run in BASIC unless statements not supported by BASIC are used in the programs. In particular, subroutines are dealt with by more sophisticated methods in QBASIC and QuickBASIC and these will not work in BASIC. This procedure is not recommended. COMPUTER IMPLEMENTATION OF SELECTED NUMERICAL METHODS In this section, we discuss the computer implementation of two extremely common numerical procedures, numerical integration and solving linear equations. Numerical Integration Our requirement for numerical integration can be satisfied by a simple trapezoidal formula and a program that implements it. The basic idea is illustrated in Fig. I-1. The integral of f(x) is to be computed between the limits a and b. To approximate this integral the interval is divided into N equal intervals of width H. For each interval, the value of f(x) at the beginning of the interval is added to the value at the end of the interval, and the sum is multiplied by H/2, where H is the width of the interval. These contributions from the N intervals are added to get the approximate value of the integral. The limit of this sum as the number of intervals becomes infinite is one definition of the Riemann integral so one would expect that a large number of small intervals could give a good approximation to the integral. In general, this expectation is correct; however, if the integrand is singular or otherwise pathological, considerable care may be needed to get the correct result, but we will not pursue this point further. The short program listed in Fig. I-2 implements this procedure. The integrand is defined on line 200; as written, it is the integrand for evaluating the power radiated by a halfwave antenna as discussed in Section 20-2. Other integrands can be written in lines 201 to 209, and all but one may be “commented out” to provide flexibility for doing a variety of integrals as 586 Appendix I FIGURE I fix) The area under the curve is approximated by trapezoids. | | ‘Ho x a b 0 1 2 3 4 N=4 needed. The program first asks for the upper and lower limits and the tolerance as a fraction of the value of the integral. The approximation for N =1 is defined. The range of integration is covered by means of a FOR...NEXT loop, and the integral is approximated by the sum of the areas of two trapezoids, 1(2). If this approximation differs from I(1) by more than the tolerance, the program returns to line 270 and doubles the number of intervals. This process is repeated until the difference between FIGURE F2 {op (yeeweensnnannnanannnsasseeesessssensnessnensnngncnsnsssSSSSSSSeOOOGAAOOHE BASIC program for in- 120 ‘= INTEC :IWTEGRATION BY TRAPEZOIDAL RULE : tegration by trapezoid 38“ se ner Lt ass : rule (integrand is defined 150 ‘sssevsssnvnssnvssssssssennscnnsesennntsonesesnsneonsstunesonnecnnnsns4sns on line 200) 10 cis 180 DIM (1024): DIM T(1024): DIM D(1024) 190 Pr= 4 * ATN(1) 200 DEF FMF (x) = ((COS(PI # xX / 2)) * 2) / (2 -X> 2) 210 INPUT "Lower limit =", LL 220 INPUT “Upper limit, 230 INPUT "Tolerance, T 240 w= 3 250 D(1) = 24 7 260 WHILE D(N) > ABS(T * I(N)) 270 No 2s N 280 a= (UL = Lb) / 290 8(0) = (UL_~ LL) * (PNF(UL) + PNF(LL)) / (2 * N) 300 FOR = 1 TON ~ 2 310 ‘S(N) = S(N) +H * (PNF(LL + J # H)) 320, next 3 330 X(N) = S(0) + S(x) 340 DON) = ABS(X(N) ~ 10M / 2)) 350. WEND 360 PRINT "N="; N, *I(N) ="; X(N), "D(H) =; DU) ‘Computers and Electromagnetic Theory 587 I(N) and I(N/2) is less than the tolerance. The number of intervals, the value of the integral, and the difference between I(N) and I(N/2) are printed. If this program is simply loaded and run with the limits —1 and 1, the computer announces that you are asking it to divide by zero. This problem occurs at the limits (in spite of the fact that the integrand actually vanishes at both limits), so it is easy to overcome by choosing limits slightly different from —1 and 1; for example, —0.999 and 0.999 instead. With these limits the program runs smoothly and gives a very satisfactory result for 512 intervals. However, the problem of dividing by zero is always a difficulty to be circumvented in one way or another. Simultaneous Linear Equations The solution of sets of simultaneous linear equations is one of the most frequently occurring tasks in mathematical physics. We limit ourselves to a nonsingular (i.e., |Ay| # 0) set of equations of the form > AyW, = D, (rl) 7 with real coefficients. The obvious approach is to use Cramer's rule to find the inverse of the matrix A and then multiply Eq. (I-1) by this inverse to obtain the W;’s. It is, however, well known that this procedure is prohibitively time consuming even for fast computers if N, the number of equations, is even moderately large. Fortunately there are other faster techniques, and we describe here the Gauss-Jordan elimination method with full pivoting. In its simplest form, elimination involves subtracting multiples of the first equation from the other equations to eliminate W, from all equations except the first. The same procedure is followed using the second equation to eliminate W, from all equations except the second, and so on. The result is a series of equations of the form W, = C, where the C;'s are derived from the D;’s in the process of elimination. A problem arises with this method when some of the diagonal elements of the coefficient matrix are small. In this case round-off errors can produce erroneous results. These are avoided by pivoting, which amounts to interchanging rows to put the largest element of the matrix on the diagonal and then eliminating the other elements in that column. The largest remaining element in the matrix is treated in the same way. After N repetitions, there remains a diagonal matrix that can be easily reduced to the identity matrix. In the process, the right-hand side is converted into the solution. It should be noted that full pivoting is not always necessary, and most sophisticated linear equation solvers pivot only if the diagonal element is smaller than some predeter- mined value. The full pivoting process is implemented by the program listed in Fig. 1-3. The program first finds the largest element in the matrix and then interchanges rows to put this largest element on the diagonal. Each 588 Appendix I FIGURE 13 3000 BASIC program for 2010 n 301s Gauss-Jordan elimination 3930 3025 dose 2038 dose 304s 2050 oss 2oeo 2065 2070 3ors 3080 boss 3090 3095 3100 bios zit bus 2120 2a hizo 23s 2s Bias 2150 diss 2iso Riss 2170 airs 3ia0 Ries 2is0 2ias 3200 2205 2240 bas 320 2aas 3230 bas 240 2as 2350 2255 3260 230s 2370 215 200 28s 2330 3a9s 2308 21s 3320 aha 2330 2335 3340 345 3330 3335 2360 Des 3370 G-J2KA: GAUSS-JORDAN ELIMINATION SUBROUTINE o LINE NUMBERS 2000, 2245, 2250, 2345 AND 2431 ARE ESSENTIAL Mat, NIB, N28, A(T,J), D(T) + should be specified by I-0 program.” Solution is generated as W(1) in + in the sane order as input, but not printed. Main progam should order + printing. ‘Identifiers ON coefficient matrix oom biggest value “oD constant vector oom work variable + IR’ row index + Tet column index + wit maximum dimension of natrices + omit number of rows + 2a number of columns + PL pivot elenent oR fork matrix ow solution matrix + Note - 1,5,X & L with or without suffixes are indices + Bnd of identifiers DIM RE(ME, 3) ‘initialize Ra(1t,3) and W(t) FOR T= 1 TO N2¥ way = pcre) RE(TE, 3) = 0! NEXT 18 ‘Diagonalize A(1t,J%) FOR TE = 1 TO N2¥ ‘Search for largest (pivot) element, Bi ‘Bi =o! FOR Jt = 1 TO N2¥ IF (R8(J%, 3) = 1) THEN 2250 FOR Ke = i 70 N2¥ TE (RR(Kt, 3) > 1) THEN PRINT “Errori ~ Matrix is singular" TF (RE(KE, 3) = 1) ‘THEN 2245 IP (Bi >= ABS(A(S%, K8))) THEN 2245 IRt = Jt Ick = Ke Bi = ABS(A(SR, Kt)) NEXT Kt NEXT 3% ‘Change RE to indicate biggest elenent in position IRY, Ick RA(IC¥, 3) = RE(ICR, 3) FT RA(IS, 2) = IRE RA(IS, 2) = Tek ‘Interchange rows to put pivot elenent on diagonal IP (IRE = ICt) THEN 2345 FOR'IA = 1-70 N2% Wa = ACRE, La) ACRE, EA) "= A(ICR, LA) A(IeR, 1A) = HL NEXT LA, Hi = W(IRE) WOIRt) = m(ICE) woes) = an ‘Divide pivot row by pivot element PL= A(tct, Ic8) IP ABS(P)'< .0000001 THEN PRINT "Error? - matrix is i11 conditioned" A(ret, Ick) =" FOR Le = 1.70 N2¥ (Icy, Lt) = A(Ict, UA) / PL NEXT 1 Dimensions of A, D, W FIGURE I-3 (continued) Computers and Electromagnetic Theory 589 2375 w(ECR) = W(ICR) / PL 2380 ° 2385 ‘Reduce elenents in colunn Ict in non-pivot rows 2390 FOR Lig = 1 TO 2. 2395, IF (L1¢ = Ick) THEN 2430 2400 P= Acta, Ic8) 2405, aqit, ret) = 0 2420 FOR Lt = 1 TO N2e 2a1s, A(LAt, Lt) = A(LIt, LA) ~ a(ICt, Lt) + 7 2420 Next Lt 2425 w(Lity) = w(nit) - woret) # 24300 NEXT Lit 2435 * 2440 NEXT 18 2445 * 2450 ‘Test for errors 2455 FOR Ke = 1 TO N2t 2460 TF (R4(Kt, 3) <> 1) THEN PRINT “Error) ~ matrix is singular": sToP 2465 NEXT KE 2470 * 2475 RETURN: ‘Return to main program from Gauss~Jordan subroutine 2480 END element in that row is divided by the largest element to reduce the diagonal element to unity. Multiples of that row are subtracted from the other rows to make the nondiagonal elements in the pivot column zero. The process is repeated, excluding the first pivot row from the search for the largest matrix element. After a number of repetitions equal to the number of equations, the matrix A is converted into the identity matrix, and the vector D is converted to the solution vector. The only feature requiring further explanation is the register matrix R, which has three columns and as many rows as there are equations and keeps track of the pivoting. The third column of this matrix starts with all zero values. After the largest element is found, the first row is changed to give the row and column location of the largest element and the third column is changed to one. The row and column indices are changed as the largest element is moved to the diagonal. On the second iteration, this row is skipped and the largest remaining element is found. If, after all rows have been processed, any element in the third column of R is not one, it means the matrix is singular and a message to that effect is displayed. Many Gauss-Jordan routines also calculate the determinant of the coefficient matrix and explicitly calculate the inverse matrix. This program can be extended to do these calculations but, since we do not use them in the text, the shorter version has been listed. Under some circumstances the dimensions of R and W may be specified by the control program, in which case apostrophes should be added to the beginning of lines 2120 and 2125 to avoid error messages. It is convenient to test the program with a simple set of equations with a known solution. A test input is listed in Fig. I-4. If this short program is loaded and the Gauss-Jordan program (G-J2KA, Fig. I-3) merged with it, then running the program should produce the answers shown. 590 Appendix I FIGURE |-4 BASIC input-output pro- gram to test Gauss- Jordan program. (Ans- wers to test problei X1=0.5, X2=1, X3= PETTTTrereeerrrereerrrTTrrrrerererrrrrrrererrrerrrrnrrriririttrrtrrrrriinyy aio "+ * 120 1 G-J_TEST: PROGRAM TO PROVIDE TEST INPUT AND PRINT OUTPUT FOR * 130 GAUSS-JORDAN EQUATION SOLVING PROGRAM ‘ 140 7 NO ESSENTIAL LINE NUMBERS * Ms ce * 350 "* : [G0 (eheeeeecesennneeeeeeaneneeaaseeennsesacenaneanaaantannnnannaaennnnnneans es 70 INPUT "M18 =", Mie 180 DIM A(MIt, mat), D(Mag), WOE) 1.5, and X4=2.) 190 N1¥ = 4: N2¥ = 4 200 A(t, 2) = a2 ACL, 2) = 22 AG, AG, 4) = 4: Da) = as Bio ala) 1) = 2: Atay 2) = 3: AG! al) 2h ba) 2 Ho AG) 1) = 3: AG! 2) = 42 AGS AGI a) Sa: oa) = a 330 Ala i) = az Alay 2) = 1: aCe, Pal 23) oa) 2a 240 cose 2000 250 PRINT PRL ="; W(L), "X2 ="; W(2), "HD <7 WOO), HO =H; HEAD 360 END Comments on Numerical Analysis We have said almost nothing about numerical analysis. Numerical analysis is too important to relegate to a few words in a text on another subject. It is important to note, however, that the very power of contemporary compu- ters makes it extremely easy to get into trouble with convergence, stability, and many of the other traps of numerical analysis. There are a number of books that deal with numerical analysis in the context of modern comput- ing; some of these are listed in the bibliography at the end of this appendix. It is useful to have one available for reference purposes when a problem arises. 14 USEFUL TIPS Several useful tips that are hard to find in the usual references are listed here. 1. It is always a good idea to test programs by doing a problem with known solutions. Problems that can be done manually are often the best for testing. The process of solution by the computer can then be followed by judiciously inserted temporary PRINT and STOP statements. For similar reasons it is best to use data sets that are just large enough to exercise all of the features of the program. In Chapter 13, for example, three frequencies are enough for checking the program. Once it is running properly, the full data set can be inserted. ‘The line PRINT "Press any key to continue. ": K§ = INPUT $(1) will stop the program until any keyboard key is pressed. KS can be any Computers and Electromagnetic Theory 591 otherwise unused string variable. It is useful for pausing to examine inputs on the screen after they have been entered. 3. To denote user choice, the lines INPUT "Do you wish to (statement) (Y/N)"; Ag IF A$ = "Y" GOTO (line number) [or THEN GOSUB (line number) . . . RETURN (line number) enable the user to choose whether or not to execute the statement. It can be used to quit, to print, or to execute a subprogram at the user’s option. As always a little care is needed to insure that entries and exits are made at the proper points to implement the desired logic. 4, Summing series. The easiest way of evaluating the sum of the first N terms of a series Sy, = DXo' J; is to use a recursion relation Sy = Swi + Twi Tw = f(Ty-1,N - 1) in a FOR NEXT or WHILE WEND loop. For example, computes the sum, S(N), of the first N + 1 terms of the series expansion for exp x. This process is used several times in various programs in the text and appendices. 5. Variables must be initialized; otherwise they will start with whatever is left in the assigned storage. That is why the second line is included in the short program in item four above. 6. Many calculations require 2. The line PI =4*ATN(1) makes it possible to type PI whenever is needed. 7. Remember that DEF FN can be used to define functions in terms of the predefined functions of BASIC as well as algebraic expressions. Thus, for example, DEF FN TANH(X) = (EXP(X) — EXP(—X)) /(EXP(X) + EXP(-X)) provides the hyperbolic tangent with the statement FN TANH(X). 8. Remember that arrays must be explicitly dimensioned if the dimen- sion exceeds 10, and it is always a good idea to dimension them. Note, for example, that S(N), I(N), and D(N) are all dimensioned in line 160 of Fig. 1-2. Dimensioning also sets all values to zero. 9. As mentioned earlier, PRINT and STOP are useful debugging tools. 10. It is sometimes useful to “comment out” lines of code by inserting Appendix 1 either REM or an apostrophe (’) at the beginning of the line. Such lines are ignored in the execution of the program, but can be easily reactivated by deleting REM or the apostrophe. 11. Finally, we repeat the early advice: “Use clever software written by other people.” BIBLIOGRAPHY The following bibliographic listing does not aim at completeness, but it does contain some useful references. Numerical Analysis 1. Hanning, R. W., Numerical Methods for Scientists and Engineers, 2nd ed. (New York: McGraw-Hill, 1973; reprinted New York: Dover, 1986). 2. Stoer, J., and R. Bulirsch, Introduction to Numerical Analysis (New York: Springer, 1983). Computer Programming 1. Knuth, Donald, The Art of Computer Programming (Reading, MA: Addison-Wesley, 1969). 2, Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetteling, Numerical Recipes: The Art of Scientific Computing (Cambridge: Cambridge University Press, 1986, 1989). This book is available in FORTRAN, Pascal, and “C” versions, and a companion volume for use with QuickBASIC version 4.5 is available and listed below. BASIC and Applications 1. “Microsoft GW-BASIC: User’s Guide and User's Reference,” Red- mond, WA, Microsoft Corporation, 1987. This manual is essential for users of GW-BASIC; similar reference manuals exist for other versions of BASIC. 2. Halvorson, Michael, and David Rygmyr, Learn BASIC Now (Redmond, WA: Microsoft Press, 1989). This tutorial on QBASIC comes with disks containing QBASIC and exercises. Apparently there is no reference manual; the extensive on-line help files serve this purpose. 3. Rugg, T., and P. Feldman, Using BASIC (Carmel, IN: Que Corpora- tion, 1990). This book is typical of many now on the market. It provides a very convenient way of learning the BASIC language. It does not contain much about solving mathematical problems 4, Rugg, T., and P. Feldman, Using QBASIC (Carmel, IN: Que Corpora tion, 1991). The same comments apply as for Using Basic. Computers and Electromagnetic Theory 593 Miller, Alan R., BASIC Programs for Scientists and Engineers (San Francisco: SYBEX Corporation, 1981). This book contains about 50 general-purpose programs and illustrations of their use. It is a useful introduction to writing technical programs in BASIC. Koonin, Steven E., Computational Physics (Reading, MA: Addison- Wesley, 1986). Koonin uses BASIC to deal with problems of real interest in physics. Some of the programs are very elaborate. The book is a good follow-on to Miller. Walker, Robert D., Numerical Methods for Engineers and Scientists (Summit, PA: TAB Books, 1987). Walker lists 21 BASIC routines for doing useful mathematical tasks covering such things as interpolation, curve fitting, complex numbers, matrix algebra, solution of sets of simultaneous linear equations, and others. There is also a useful menu routine that provides convenient access to the individual programs. The programs are arranged to deal with mathematical problems, but they can be integrated into other programs. Sprott, Julien C., Numerical Recipes in BASIC (Cambridge: Cambridge University Press, 1991). A companion volume to Numerical Recipes, this book does not contain all of the text from Numerical Recipes; both are needed. The routines and examples were prepared to work with QuickBASIC 4.5.

You might also like