Computational Physics

Computational Physics 9
Dr.AstonCole Profile Pic
Dr.AstonCole,United Kingdom,Researcher
Published Date:10-07-2017
Your Website URL(Optional)
Comment
Computational Physics Richard Fitzpatrick Professor of Physics The University of Texas at AustinContents 1 Introduction 8 1.1 Intended Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.2 Major Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.3 Purpose of Course . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4 Course Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.5 Programming Methodologies . . . . . . . . . . . . . . . . . . . . . 9 1.6 Scientific Programming Languages . . . . . . . . . . . . . . . . . . 11 2 Scientific Programming in C 13 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.3 Expressions and Statements . . . . . . . . . . . . . . . . . . . . . . 15 2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.5 Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.6 Data Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . 26 2.7 Structure of a C Program . . . . . . . . . . . . . . . . . . . . . . . . 33 2.8 Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.9 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.10 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 2.11 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 22.12 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 2.13 Character Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 2.14 Multi-File Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 75 2.15 Command Line Parameters. . . . . . . . . . . . . . . . . . . . . . . 77 2.16 Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 2.17 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 2.18 C++ Extensions to C . . . . . . . . . . . . . . . . . . . . . . . . . . 83 2.19 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 2.20 Variable Size Multi-Dimensional Arrays . . . . . . . . . . . . . . . . 89 2.21 The CAM Graphics Class . . . . . . . . . . . . . . . . . . . . . . . . 93 3 Integration of ODEs 101 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 3.2 Euler’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 3.3 Numerical Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 3.4 Numerical Instabilities . . . . . . . . . . . . . . . . . . . . . . . . . 106 3.5 Runge-Kutta Methods . . . . . . . . . . . . . . . . . . . . . . . . . 106 3.6 An Example Fixed-Step RK4 routine . . . . . . . . . . . . . . . . . 109 3.7 An Example Calculation . . . . . . . . . . . . . . . . . . . . . . . . 111 3.8 Adaptive Integration Methods . . . . . . . . . . . . . . . . . . . . . 113 3.9 An Example Adaptive-Step RK4 Routine . . . . . . . . . . . . . . . 117 3.10 Advanced Integration Methods . . . . . . . . . . . . . . . . . . . . 121 33.11 The Physics of Baseball Pitching . . . . . . . . . . . . . . . . . . . . 121 3.12 Air Drag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 3.13 The Magnus Force . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 3.14 Simulations of Baseball Pitches . . . . . . . . . . . . . . . . . . . . 127 3.15 The Knuckleball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 4 The Chaotic Pendulum 140 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 4.2 Analytic Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 4.3 Numerical Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 4.4 Validation of Numerical Solutions . . . . . . . . . . . . . . . . . . . 148 4.5 The Poincar´e Section . . . . . . . . . . . . . . . . . . . . . . . . . . 151 4.6 Spatial Symmetry Breaking . . . . . . . . . . . . . . . . . . . . . . 152 4.7 Basins of Attraction . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 4.8 Period-Doubling Bifurcations . . . . . . . . . . . . . . . . . . . . . 163 4.9 The Route to Chaos . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 4.10 Sensitivity to Initial Conditions . . . . . . . . . . . . . . . . . . . . 173 4.11 The Definition of Chaos . . . . . . . . . . . . . . . . . . . . . . . . 179 4.12 Periodic Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 4.13 Further Investigation . . . . . . . . . . . . . . . . . . . . . . . . . . 184 5 Poisson’s Equation 189 45.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 5.2 1-D Problem with Dirichlet Boundary Conditions . . . . . . . . . . 190 5.3 An Example Tridiagonal Matrix Solving Routine . . . . . . . . . . . 193 5.4 1-D problem with Mixed Boundary Conditions . . . . . . . . . . . . 194 5.5 An Example 1-D Poisson Solving Routine . . . . . . . . . . . . . . . 195 5.6 An Example Solution of Poisson’s Equation in 1-D . . . . . . . . . . 197 5.7 2-D problem with Dirichlet Boundary Conditions . . . . . . . . . . 197 5.8 2-d Problem with Neumann Boundary Conditions . . . . . . . . . . 201 5.9 The Fast Fourier Transform . . . . . . . . . . . . . . . . . . . . . . 202 5.10 An Example 2-D Poisson Solving Routine . . . . . . . . . . . . . . . 207 5.11 An Example Solution of Poisson’s Equation in 2-D . . . . . . . . . . 211 5.12 Example 2-D Electrostatic Calculation . . . . . . . . . . . . . . . . 213 5.13 3-D Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 6 The Diffusion Equation 218 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 6.2 1-D Problem with Mixed Boundary Conditions . . . . . . . . . . . . 219 6.3 An Example 1-D Diffusion Equation Solver . . . . . . . . . . . . . . 220 6.4 An Example 1-D Solution of the Diffusion Equation . . . . . . . . . 221 6.5 von Neumann Stability Analysis . . . . . . . . . . . . . . . . . . . . 224 6.6 The Crank-Nicholson Scheme . . . . . . . . . . . . . . . . . . . . . 225 6.7 An Improved 1-D Diffusion Equation Solver . . . . . . . . . . . . . 226 56.8 An Improved 1-D Solution of the Diffusion Equation . . . . . . . . 228 6.9 2-D Problem with Dirichlet Boundary Conditions . . . . . . . . . . 229 6.10 2-D Problem with Neumann Boundary Conditions . . . . . . . . . . 231 6.11 An Example 2-D Diffusion Equation Solver . . . . . . . . . . . . . . 232 6.12 An Example 2-D Solution of the Diffusion Equation . . . . . . . . . 236 6.13 3-D Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 7 The Wave Equation 238 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 7.2 The 1-D Advection Equation . . . . . . . . . . . . . . . . . . . . . . 238 7.3 The Lax Scheme . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 7.4 The Crank-Nicholson Scheme . . . . . . . . . . . . . . . . . . . . . 243 7.5 Upwind Differencing . . . . . . . . . . . . . . . . . . . . . . . . . . 245 7.6 The 1-D Wave Equation . . . . . . . . . . . . . . . . . . . . . . . . 248 7.7 The 2-D Resonant Cavity . . . . . . . . . . . . . . . . . . . . . . . . 252 8 Particle-in-Cell Codes 265 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 8.2 Normalization Scheme . . . . . . . . . . . . . . . . . . . . . . . . . 266 8.3 Solution of Electron Equations of Motion . . . . . . . . . . . . . . . 267 8.4 Evaluation of Electron Number Density . . . . . . . . . . . . . . . . 267 8.5 Solution of Poisson’s Equation . . . . . . . . . . . . . . . . . . . . . 268 68.6 An example 1-D PIC Code . . . . . . . . . . . . . . . . . . . . . . . 269 8.7 Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 8.8 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 9 Monte-Carlo Methods 284 9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 9.2 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 9.3 Distribution Functions . . . . . . . . . . . . . . . . . . . . . . . . . 291 9.4 Monte-Carlo Integration . . . . . . . . . . . . . . . . . . . . . . . . 294 9.5 The Ising Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 71 INTRODUCTION 1 Introduction 1.1 Intended Audience These set of lecture notes are designed for an upper-division undergraduate course on computational physics. 1.2 Major Sources The sources which I have consulted most frequently whilst developing course material are as follows: C/C++ PROGRAMMING: Software engineering in C, P.A. Darnell, and P.E. Margolis (Springer-Verlag, New York NY, 1988). TheC++programminglanguage,2ndedition,B.Stroustrup(Addison-Wesley, Reading MA, 1991). Schaum’s outline: Programming with C, 2nd edition, B. Gottfried (McGraw- Hill, New York NY, 1996). Schaum’soutline: ProgrammingwithC++,2ndedition,J.R.Hubbard(McGraw- Hill, New York NY, 2000). NUMERICAL METHODS AND COMPUTATIONAL PHYSICS: Computational physics, D. Potter (Wiley, New York NY, 1973). Numerical recipes in C: the art of scientific computing,W.H.Press,S.A.Teukol- sky,W.T.Vettering,andB.R.Flannery(CambridgeUniversityPress,Cam- bridge UK, 1992). Computational physics,N.J.Giordano(Prentice-Hall,UpperSaddleRiverNJ, 1997). Numerical methods for physics,2ndedition,A.L.Garcia(Prentice-Hall,Upper Saddle River NJ, 2000). 81.3 Purpose of Course 1 INTRODUCTION PHYSICS OF BASEBALL: The physics of baseball, R.K. Adair (Harper & Row, New York NY, 1990). The physics of sports, A.A. Armenti, Jr., Ed. (American Institute of Physics, New York NY, 1992). CHAOS: Chaos in a computer-animated pendulum, R.L. Kautz, Am. J. Phys. 61, 407 (1993). Nonlinear dynamics and chaos, S.H. Strogatz, (Addison-Wesley, Reading MA, 1994). Chaos: An introduction to dynamical systems, K.T. Alligood, T.D. Sauer, and J.A. Yorke, (Springer-Verlag, New York NY, 1997). 1.3 Purpose of Course The purpose of this course is demonstrate to students how computers can enable ustobothbroadenanddeepenourunderstandingofphysicsbyvastlyincreasing the range of mathematical calculations which we can conveniently perform. 1.4 Course Philosophy My approach to computational physics is to write self-contained programs in a high-levelscientificlanguage—i.e.,eitherFORTRANorC/C++. Ofcourse,there are many other possible approaches, each with their own peculiar advantages and disadvantages. It is instructive to briefly examine the available options. 1.5 Programming Methodologies Basically, there are three possible methods by which we could perform the nu- merical calculations which we are going to encouter during this course. 91.5 Programming Methodologies 1 INTRODUCTION Firstly, we could use a mathematical software package, such as MATHEMAT- 1 2 3 ICA , MAPLE or MATLAB. The main advantage of these packages is that they facilitate the very rapid coding up of numerical problems. The main disadvan- tage is that they produce executable code which is interpreted, rather than com- piled. Compiled code is translated directly from a high-level language into ma- chine code instructions, which, by definition, are platform dependent—after all, an Intel x86 chip has a completely different instruction set to a Power-PC chip. Interpreted code is translated from a high-level language into a set of meta-code instructions which are platform independent. Each meta-code instruction is then translated into a fixed set of machine code instructions which is peculiar to the particular hardware platform on which the code is being run. In general, inter- preted code is nowhere near as efficient, in terms of computer resource utiliza- tion, as compiled code: i.e., interpreted code run a lot slower than equivalent compiled code. Thus, although MATHEMATICA, MAPLE, and MATLAB are ideal environments in which to perform relatively small calculations, they are not suit- ableforfull-blownresearchprojects,sincethecodewhichtheyproducegenerally runs far too slowly. Secondly, we could write our own programs in a high-level language, but use calls to pre-written, pre-compiled routines in commonly available subroutine li- 4 5 6 braries, such as NAG, LINPACK, and ODEPACK, to perform all of the real numericalwork. Thisistheapproachusedbythemajorityofresearchphysicists. Thirdly, we could write our own programs—completely from scratch—in a high-level language. This is the approach used in this course. I have opted not to use pre-written subroutine libraries, simply because I want students to develop the ability to think for themselves about scientific programming and numerical techniques. Students should, however, realize that, in many cases, pre-written library routines offer solutions to numerical problems which are pretty hard to improve upon. 1 See http://www.wolfram.com 2 See http://www.maplesoft.com 3 See http://www.mathworks.com 4 See http://www.nag.com 5 See http://www.netlib.org 6 ibid. 101.6 Scientific Programming Languages 1 INTRODUCTION 1.6 Scientific Programming Languages What is the best high-level language to use for scientific programming? This, unfortunately,isahighlycontentiousquestion. Overtheyears,literallyhundreds ofhigh-levellanguageshavebeendeveloped. However,fewhavestoodthetestof time. Manylanguages(e.g.,Algol,Pascal,Haskell)canbedismissedasephemeral computersciencefads. Others(e.g.,Cobol,Lisp,Ada)aretoospecializedtoadapt for scientific use. Let us examine the remaining options: FORTRAN 77: FORTRAN was the first high-level programming language to be developed: in fact, it predates the languages listed below by decades. Be- fore the advent of FORTRAN, all programming was done in assembler code Moreover, FORTRAN was specifically designed for scientific computing. In- deed,intheearlydaysofcomputersallcomputingwasscientificinnature— i.e., physicists and mathematicians were the original computer scientists FORTRAN’s main advantages are that it is very straightforward, and it in- terfaceswellwithmostcommonlyavailable,pre-writtensubroutinelibraries (since these libraries generally consist of compiled FORTRAN code). FOR- TRAN’s main disadvantages are all associated with its relative antiquity. For instance. FORTRAN’s control statements are fairly rudimentary, whereas its input/output facilities are positively paleolithic. FORTRAN 90: This language is a major extension to FORTRAN 77 which does away with many of the latter language’s objectionable features. In addition, many “modern” features, such as dynamic memory allocation, are included in the language for the first time. The major disadvantage of this language istheabsenceofaninexpensivecompiler. Thereseemslittleprospectofthis situation changing in the near future. C: This language was originally developed by computer scientists to write op- erating systems. Indeed, all UNIX operating systems are written in C. C is, consequently,anextremelyflexibleandpowerfullanguage. Amongstitsma- jor advantages are its good control statements and excellent input/output facilities. C’s main disadvantage is that, since it was not specifically written to be a scientific language, some important scientific features (e.g., complex 111.6 Scientific Programming Languages 1 INTRODUCTION arithmetic) are missing. Although C is a high-level language, it incorporates many comparatively low-level features, such as pointers (this is hardly sur- prisingly, since C was originally designed to write operating systems). The low-level features of C—in particular, the rather primitive implementation of arrays—sometimes make scientific programming more complicated than need be the case, and undoubtedly facilitate programming errors. On the other hand, these features allow scientific programmers to write extremely efficient code. Since efficiency is generally the most important concern in scientific computing, the low-level features of C are, on balance, advanta- geous. C++: This language is a major extension of C whose main aim is to facilitate object-orientated programming. Object-orientation is a completely different approach to programming than the more traditional procedural approach: it is particularly well suited to large projects involving many people who are each writing different segments of the same code. However, object- orientation represents a large, and somewhat unnecessary, overhead for the type of straightforward, single person programming tasks considered in this course. Note, however, that C++ incorporates some non-object-orientated extensions to C which are extremely useful. Of the above languages, we can immediately rule out C++, because object- orientationisanunnecessarycomplication(atleast,forourpurposes),andFOR- TRAN 90, because of the absence of an inexpensive compiler. The remaining options are FORTRAN 77 and C. I have chosen to use C (augmented by some of theuseful,non-object-orientatedfeaturesofC++)inthiscourse,simplybecause I find the archaic features of FORTRAN 77 too embarrassing to teach students in the 21st century. 122 SCIENTIFIC PROGRAMMING IN C 2 Scientific Programming in C 2.1 Introduction As we have already mentioned, C is a flexible, extremely powerful, high-level programming language which was initially designed for writing operating sys- tems and system applications. In fact, all UNIX operating systems, as well as most UNIX applications (e.g., text editors, window managers, etc.) are written in C. However, C is also an excellent vehicle for scientific programming, since, almost by definition, a good scientific programming language must be powerful, flexible, and high-level. Having said this, many of the features of C which send computer scientists into raptures are not particularly relevant to the needs of the scientificprogrammer. Hence,inthefollowing,weshallonlydescribethatsubset oftheClanguagewhichisreallynecessarytowritescientificprograms. Itmaybe objected that our cut-down version of C bears a suspicious resemblance to FOR- TRAN. However, this resemblance is hardly surprising. After all, FORTRAN is a high-level programming language which was specifically designed with scientific computing in mind. As discussed previously, C++ is an extension of the C language whose main aimistofacilitateobject-orientatedprogramming. Theobject-orientatedfeatures of C++ are superfluous to our needs in this course. However, C++ incorporates some new, non-object-orientated features which are extremely useful to the sci- entificprogrammer. Weshallbrieflydiscussthesefeaturestowardstheendofthis section. Finally, we shall describe some prewritten C++ classes which allow us toincorporatecomplexarithmetic(whichisnotpartoftheClanguage),variable size arrays, and graphics into our programs. 2.2 Variables Variable names in C can consist of letters and numbers in any order, except that thefirstcharactermustbealetter. Namesare case sensitive,soupper-andlower- case letters are not interchangeable. The underscore character (_) can also be 132.2 Variables 2 SCIENTIFIC PROGRAMMING IN C included in variable names, and is treated as a letter. There is no restriction on thelengthofnamesinC.Ofcourse,variablenamesarenotallowedtoclashwith keywords that play a special role in the C language, such as int, double, if, return, void, etc. The following are examples of valid variable names in C: x c14 area electron_mass TEMPERATURE The C language supports a great variety of different data types. However, the twodatatypeswhichoccurmostofteninscientificprogramsareinteger,denoted int, and floating-point, denoted double. (Note that variables of the most basic floating-point data type float are not generally stored to sufficient precision by the computer to be of much use in scientific programming.) The data type (int or double)ofeveryvariableinaCprogrammustbedeclaredbeforethatvariable can appear in an executable statement. Integer constants in C are denoted, in the regular fashion, by strings of arabic numbers: e.g., 0 57 4567 128933 Floating-pointconstantscanbewrittenineitherregularorscientificnotation: e.g., 0.01 70.456 3e+5 .5067e-16 Strings are mainly used in scientific programs for data input and output pur- poses. A string consists of any number of consecutive characters (including blanks) enclosed in double quotation marks: e.g., "red" "Austin TX, 78723" "512-926-1477" Line-feeds can be incorporated into strings via the escape sequence \n: e.g., "Line 1\nLine 2\nLine 3" The above string would be displayed on a computer terminal as Line 1 Line 2 Line 3 142.3 Expressions and Statements 2 SCIENTIFIC PROGRAMMING IN C A declaration associates a group of variables with a specific data type. As mentioned previously, all variables must be declared before they can appear in executable statements. A declaration consists of a data type followed by one or more variable names, ending in a semicolon. For instance, int a, b, c; double acc, epsilon, t; In the above, a, b, and c are declared to be integer variables, whereas acc, epsilon, and t are declared to be floating-point variables. A type declaration can also be used to assign initial values to variables. Some examples of how to do this are given below: int a = 3, b = 5; double factor = 1.2E-5; Here, the integer variables a and b are assigned the initial values 3 and 5, re- spectively,whereasthefloating-pointvariablefactorisassignedtheinitialvalue −5 1.2×10 . Note that there is no restriction on the length of a type declaration: such a declaration can even be split over many lines, so long as its end is signaled by a semicolon. However, all declaration statements in a program (or program segment) must occur prior to the first executable statement. 2.3 Expressions and Statements An expression represents a single data item—usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are either true or false. However,inC,theconditionstrueandfalsearerepresentedbytheintegervalues 1 and 0, respectively. Several simple expressions are given below: a + b x = y 152.3 Expressions and Statements 2 SCIENTIFIC PROGRAMMING IN C t = u + v x = y ++j Thefirstexpression,whichemploystheadditionoperator(+),representsthesum of the values assigned to variables a and b. The second expression involves the assignment operator (=), and causes the value represented by y to be assigned to x. In the third expression, the value of the expression (u + v) is assigned to t. The fourth expression takes the value 1 (true) if the value of x is less than or equaltothevalueof y. Otherwise,theexpressiontakesthevalue 0(false). Here, = is a relational operator that compares the values of x and y. The final example causes the value of j to be increased by 1. Thus, the expression is equivalent to j = j + 1 The increment (by unity) operator ++ is called a unary operator, because it only possesses one operand. A statement causes the computer to carry out some definite action. There are three different classes of statements in C: expression statements, compound statements, and control statements. An expression statement consists of an expression followed by a semicolon. The execution of such a statement causes the associated expression to be evalu- ated. For example: a = 6; c = a + b; ++j; The first two expression statements both cause the value of the expression on the right of the equal sign to be assigned to the variable on the left. The third expression statement causes the value of j to be incremented by 1. Again, there is no restriction on the length of an expression statement: such a statement can even be split over many lines, so long as its end is signaled by a semicolon. Acompoundstatementconsistsofseveralindividualstatementsenclosedwithin a pair of braces . The individual statements may themselves be expression 162.3 Expressions and Statements 2 SCIENTIFIC PROGRAMMING IN C statements,compoundstatements,orcontrolstatements. Unlikeexpressionstate- ments, compound statements do not end with semicolons. A typical compound statement is shown below: pi = 3.141593; circumference = 2. pi radius; area = pi radius radius; This particular compound statement consists of three expression statements, but acts like a single entity in the program in which it appears. A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent either a number or a string. When a program is compiled,eachoccurrenceofasymbolicconstantisreplacedbyitscorresponding character sequence. Symbolic constants are usually defined at the beginning of a program, by writing define NAME text where NAME represents a symbolic name, typically written in upper-case letters, andtextrepresentsthesequenceofcharactersthatisassociatedwiththatname. Note that text does not end with a semicolon, since a symbolic constant defi- nition is not a true C statement. In fact, during compilation, the resolution of symbolicnamesisperformed(bytheCpreprocessor)beforethestartoftruecom- pilation. For instance, suppose that a C program contains the following symbolic constant definition: define PI 3.141593 Suppose, further, that the program contains the statement area = PI radius radius; During the compilation process, the preprocessor replaces each occurrence of the symbolic constant PI by its corresponding text. Hence, the above statement becomes area = 3.141593 radius radius; 172.4 Operators 2 SCIENTIFIC PROGRAMMING IN C Symbolic constants are particularly useful in scientific programs for representing constants ofnature, suchasthemassofanelectron, thespeedoflight, etc. Since these quantities are fixed, there is little point in assigning variables in which to store them. 2.4 Operators As we have seen, general expressions are formed by joining together constants and variables via various operators. Operators in C fall into five main classes: arithmetic operators, unary operators, relational and logical operators, assignment operators,andtheconditionaloperator. Letus,now,examineeachoftheseclasses in detail. There are four main arithmetic operators in C. These are: addition + subtraction - multiplication division / Unbelievably, there is no built-in exponentiation operator in C (C was written by computer scientists) Instead, there is a library function (pow) which carries out this operation (see later). It is poor programming practice to mix types in arithmetic expressions. In other words, the two operands operated on by the addition, subtraction, multi- plication, or division operators should both be either of type int or type double. The value of an expression can be converted to a different data type by prepend- ing the name of the desired data type, enclosed in parenthesis. This type of construction is known as a cast. Thus, to convert an integer variable j into a floating-point variable with the same value, we would write (double) j Finally, to avoid mixing data types when dividing a floating-point variable x by an integer variable i, we would write 182.4 Operators 2 SCIENTIFIC PROGRAMMING IN C x / (double) i Of course, the result of this operation would be of type double. The operators within C are grouped hierarchically according to their prece- dence (i.e., their order of evaluation). Amongst the arithmetic operators, and / have precedence over + and -. In other words, when evaluating expressions, C performs multiplication and division operations prior to addition and subtrac- tion operations. Of course, the rules of precedence can always be bypassed by judicious use of parentheses. Thus, the expression a - b / c + d is equivalent to the unambiguous expression a - (b / c) + d since division takes precedence over addition and subtraction. The distinguishing feature of unary operators is that they only act on single operands. The most common unary operator is the unary minus, which occurs when a numerical constant, variable, or expression is preceded by a minus sign. Note that the unary minus is distinctly different from the arithmetic operator (-) which denotes subtraction, since the latter operator acts on two separate operands. The two other common unary operators are the increment operator, ++, and the decrement operator, . The increment operator causes its operand to be increased by 1, whereas the decrement operator causes its operand to be decreased by 1. For example, i is equivalent to i = i - 1. A cast is also considered to be a unary operator. Note that unary operators have precedence over arithmetic operators. Hence, - x + y is equivalent to the unambiguous expression (-x) + y, since the unary minus operator has precedence over the addition operator. Notethatthereisasubtledistinctionbetweentheexpressions a++and ++a. In the former case, the value of the variable a is returned before it is incremented. In the latter case, the value of a is returned after incrementation. Thus, b = a++; 192.4 Operators 2 SCIENTIFIC PROGRAMMING IN C is equivalent to b = a; a = a + 1; whereas b = ++a; is equivalent to a = a + 1; b = a; There is a similar distinction between the expressions a and a. There are four relational operators in C. These are: less than less than or equal to = greater than greater than or equal to = The precedence of these operators is lower than that of arithmetic operators. Closelyassociatedwiththerelationaloperatorsarethetwo equality operators: equal to == not equal to = Theprecedenceoftheequalityoperatorsisbelowthatoftherelationaloperators. The relational and equality operators are used to form logical expressions, whichrepresentconditionsthatareeithertrueorfalse. Theresultingexpressions are of type int, since true is represented by the integer value 1 and false by the integer value 0. For example, the expression i j is true (value 1) if the value of i is less than the value of j, and false (value 0) otherwise. Likewise, the expression j == 3 is true if the value of j is equal to 3, and false otherwise. C also possess two logical operators. These are: 20

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.