2nd year computational physics week 1 (standard):...

71
2nd Year Computational Physics Week 1 (standard): Getting acquainted with C 1

Upload: hoangnguyet

Post on 19-Mar-2018

214 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

2nd YearComputational PhysicsWeek 1 (standard): Getting

acquainted with C

1

Page 2: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Last compiled September 28, 2017

2

Page 3: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Contents

1 Introduction 6

1.1 Getting Acquainted . . . . . . . . 8

1.2 Introduction to Program Logic andFlow Charts . . . . . . . . . . . . 8

2 Prelab Questions 12

3 Hello, world! 14

3.1 Background . . . . . . . . . . . . 14

3.1.1 Introduction to Linux . . . 14

3.1.2 Program Structure . . . . 16

3.1.3 Program Compilation . . . 21

3.1.4 Standard Libraries and Ba-sic Data Output . . . . . 23

3.2 Procedure . . . . . . . . . . . . . 24

3

Page 4: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

3.3 Example Code . . . . . . . . . . . 24

4 Evaluating a Simple Function 26

4.1 Background . . . . . . . . . . . . 26

4.1.1 Data Types and Precision 26

4.1.2 Operators . . . . . . . . . 29

4.1.3 User Input . . . . . . . . 29

4.2 Procedure . . . . . . . . . . . . . 32

4.3 Example Code . . . . . . . . . . . 33

5 Data Files and Plotting 35

5.1 Background . . . . . . . . . . . . 35

5.1.1 Exporting Data in C . . . 35

5.1.2 Plotting Data . . . . . . . 37

5.2 Procedure . . . . . . . . . . . . . 40

5.3 Example Code . . . . . . . . . . . 40

4

Page 5: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

6 Loops and Logic Statements 44

6.1 Background . . . . . . . . . . . . 44

6.1.1 If Function and Boolean Ob-jects . . . . . . . . . . . . 44

6.1.2 Loops in C . . . . . . . . 46

6.1.3 Series and Sequences . . . 49

6.2 Procedure . . . . . . . . . . . . . 51

6.3 Example Code . . . . . . . . . . . 51

7 Bonus Section: Special Functionsand Recurrence Relations 64

7.1 Background . . . . . . . . . . . . 64

7.1.1 Series Representations of BesselFunctions . . . . . . . . . 64

7.2 Procedure (One Bonus Mark) . . . 65

7.3 Example Code . . . . . . . . . . . 67

5

Page 6: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

1 Introduction

Computation is of fundamental importance in physics.While many physical systems can be described bysimple analytical rules, there are yet many morethat are analytically intractable. Even seeminglysimple systems blow up in complexity when theycontain any more than one or two elements. Com-putational and numerical techniques make thesepreviously difficult or impossible to solve systemswithin reach, and as a result are at the foundationof modern physics.

The purpose of these labs is to introduce you tosome of the basics of computer programming, aswell as some of most important techniques in com-putational physics. At the end of these labs you willbe able to perform a host of tasks using numericaltechniques, including solving systems of equations,series expansions, differentiation and integration,root finding and solving ordinary differential equa-tions, among other things. The language of choicefor these labs is C, though the techniques and logic

6

Page 7: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

are universal.

The course consists of four 6 hour lab sessions, bro-ken up into 3 hour slots. You will be expectedto have read through the lab in detail and an-swered the prelab questions before arrival (prelabsare marked). During the session you will workthrough the assigned problems, with the guidanceof your lab demonstrators. Although you are notworking in groups, communication with your peersis encouraged, but code copying is frowned upon.You must submit all hand drawn and printed fig-ures in hard copy with your lab book. Make sureyou finish the prelabs, including all of theflowcharts, before the lab session. You willhave to submit your lab book at the end of the dayof your lab session. Your code must also be emailedto Laurence at [email protected] by5pm on the day of your session.

For further information on common mistakes andproper style when drawing flowcharts and coding inC, and how to code C at home, it is highly recom-mended that you read the documents on the second

7

Page 8: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

year labs website. READ THESE.

1.1 Getting Acquainted

You can’t build a house until you can swing a ham-mer. This week we will work through some ofthe most important building blocks in any pro-gram. We work through the use of the Linux sys-tem terminal and program compilation, basic pro-gram flow and logic, data types, input and outputoperations and loops. We will use these in the con-text of mathematical series and sequences, and endwith an interesting example of series solutions todifferential equations.

1.2 Introduction to Program Logicand Flow Charts

At its most basic level, a program is simply a chainof simple logical operations which you get a com-puter to work though sequentially. While most

8

Page 9: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

programs are far from simple in their entirety, thiscomplexity is a result of scale, and they can still bedecomposed into a sequence of simple operations.Given that the programmer is building complicatedalgorithms from simple rules, planning is key, elseyou are likely to find yourself in, I think the tech-nical term is ‘a big horrible mess’.

It is of paramount importance when writing a pro-gram that the core stream of logic behind the pro-gram is sound. To this end, it is common practiceto employ the use of flow charts to describe the flowof a program, from its execution to its completion.The basic (and rather obvious) flow of pretty muchevery program ever goes as follows:

start program

do stuff

end program

9

Page 10: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

where do stuff can contain many iterations of thissame pattern. The basic operations that make upprogramming are presented in Table 1, along withtheir conventional flow chart representation.

Symbol Purpose Description→ Flow

LineUsed to indicate flow oflogic by connecting sym-bols.

Start/StopUsed to represent thestart and end of flowchart.

Input/OutputUsed to indicate inputor output operation.

ProcessingUsed to indicate arith-metic operations anddata manipulation.

Decision Used to indicate truefalse discrimination.

Table 1:

As a slightly less trivial example consider the fol-lowing flow chart:

10

Page 11: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Start

Declare variables num1, num2 and sum

read num1 and num2 from user input

sum←a+b

Display sum

Stop

which sums two numbers input by the user and dis-plays the result on screen. (Note: don’t worry toomuch about the step under Start for now, it will beexplained later...). As another example consider:

11

Page 12: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Start

Declare variables a, b and c

read a, b and c

is a>b?

is b>c? is a>c?

Print b Print c Print a

Stop

False True

True False True

which finds the largest of the three numbers inputby the user.

2 Prelab Questions

Note: You should read through the entirety of thelab before attempting the pre-lab questions.

1. Draw a flow chart to print the numbers 1-1012

Page 13: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

in order.

2. Draw a flow chart for how you would recur-sively compute the factorial, n! for a giveninteger n. Hint: There should be a termi-nation condition when n = 1.

3. Draw a flow-chart for question 3 of the pro-cedure in section 6.2 showing how you usethe Euler Method to find a series expressionfor π.

13

Page 14: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

3 Hello, world!

3.1 Background

3.1.1 Introduction to Linux

The part 2 lab computers are running Linux oper-ating systems. While having a graphical interface,the advantage of Linux over Windows is access tothe terminal, in which you can access all elementsof the operating system via command-line inputs.This is extremely useful when compiling and run-ning simple programs, as it makes such tasks simpleone line inputs, and removes the need for 3rd partysoftware with graphical interfaces.

Table 2 contains a list of basic terminal commands;remember them, as you will use them often. As anexample, if I were to create a working directory‘/home/Lab_1’ containing the file ‘Lab_1.c’ andopen it in the default text editor, I would write:

1mkdir ˜/Lab1; cd Lab_1; touch Lab_1.c; geditLab_1.c;

14

Page 15: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Command Descriptioncd Move to new directory

mkdir Create new directorycp Copy filemv Move filerm Remove filels View contents of cur-

rent directorytouch Create filepwd Display working direc-

tory/ Location of home di-

rectory; End of line

Table 2: List of basic Linux terminal commands.

15

Page 16: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

3.1.2 Program Structure

The language of choice for these labs is C. All Cprograms are built around one main file, which wewill call, surprise surprise, main.c. This file mustcontain a function called ‘main’ which returns aninteger. The execution of the ‘main’ function de-fines the execution of the C program. The syntaxfor declaring a function in C is the following:

16

Page 17: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

1// main.c2

3int main()4{5// do stuff here6return(0);7}

where round brackets encapsulate the required func-tion inputs, and curly brackets encapsulate the func-tions execution. This function takes no inputs andreturns 0. Note the semi-colon, this tells the com-piler that there is a line-break in the program. Youmust include a semi-colon at the end of every ac-tion within the program or it will not compile. Cdoes not have restrictions on number of lines orvariable names, but is case sensitive.

Of course we are not limited to just one function;within main() we can call other functions, whichin turn can call further functions etc. To use a newfunction we must do 2 things, declare it and defineit.

17

Page 18: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

To Declare a function you simply write its nameand type, as well as the type of the inputs, for ex-ample int function(int);. You must do thisso that the compiler knows the function exists, anddoesn’t complain when you reference it later in yourcode.

To Define a function you write it out in full, as formain() above. You can of course (as with main()above) do both of these stages at once, though theyshould be conceptually separated, as we will discussbelow.

No function can be declared or defined within an-other function, so must be declared/defined beforemain(). One method is to simply declare/definenew functions above main() in main.c i.e.

1// main.c2int do_more_stuff(int input)3{4// do more stuff, define some_integer.5return(some_integer);6}7//////////////////////8int main()

18

Page 19: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

9{10// do stuff here, define input11do_more_stuff(input);12return(0);13}

where do_more_stuff(int input) takes an in-teger as an input and returns an integer. Alter-natively we can write our non-main() functions inanother C file called a library file, for example

1// do_more_stuff.c2int do_more_stuff(int input)3{4// do more stuff, define some_integer.5return(some_integer);6}

We can then compile this file along with main.cinto an executable as we will discuss shortly. Filesending with .c are referred collectively as sourcefiles. This convention is desirable as our file nam-ing scheme now matches our file functionality (andclean code = good code...). This introduces a newproblem however, as nowhere in main.c is there a

19

Page 20: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

declaration/definition of int do_more_stuff(intinput) before it is used. Thus when we call thisfunction in main.c, it looks like an unknown en-tity, and the program will not compile. The solu-tion is to use what is known as a header file, whichconventionally has file type do_more_stuff.h. Thisfile contains just the deceleration of the functionname, not the function contents, and it is includedat the top of main.c with the #include com-mand, so that everywhere in main.c is it clear thatint do_more_stuff(int input) exists. Thusint do_more_stuff(int input) is declared indo_more_stuff.h, but defined in do_more_stuff.c.Explicitly:

1// do_more_stuff.h2int do_more_stuff(int);

1// do_more_stuff.c2int do_more_stuff(int input)3{4// do more stuff, define some_integer.5return(some_integer);6}

20

Page 21: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

1// main.c2#include "do_more_stuff.h"3

4int main()5{6// do stuff here, define input7do_more_stuff(input);8return(0);9}

3.1.3 Program Compilation

Now that we have the basic structure of our code,we need to compile it into an executable program.This is done by a program called a compiler, whichacts on our code in several stages:

1. Pre-processing is the first stage of compi-lation. It reads all #include statements inall source files, and takes note of all declaredfunctions and variables. Note that the pre-processing stage must include declarations ofall functions and global variables used in any

21

Page 22: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

source code functions, else the next stage willfail.

2. Compilation takes the output of the pre-processor and all source code files (.c) andcompiles them into object files (.o), whichare machine readable.

3. Linking takes all object files and links themtogether into one executable.

While it is important to know how the processworks, and it is possible to separate the stages ofcompilation, producing intermediary files, it is notnecessary for our purposes. We will be using thecompiler gcc, which takes care of all these stagesbehind the scenes. To run gcc from terminal andcompile a program, we simply navigate to the di-rectory containing the source code files, and enter:

1gcc list_of_source_files -o executable_name;

where -o just tells the compiler to perform theabove stages without outputting any intermediary

22

Page 23: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

files. To compile the above example we would en-ter:

1gcc main.c do_more_stuff.c -o executable;

leaving us with an executable which we can run inthe current directory by entering ./executablein terminal.

3.1.4 Standard Libraries and Basic DataOutput

As fun as it is writing your own libraries of func-tions to use in your main() function, there exista host of pre-existing libraries of functions whichcan be used to make your life easier. In fact whenpeople talk about ‘writing in C’, they really mean‘writing in C using the standard library set’. So im-portant are standard libraries, that when updatedthey can fundamentally change the way program-ming is done in any given language.

The first library we will use is stdio, accessedby including <stdio.h> in the relevant source

23

Page 24: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

files. This library contains functions which dealswith data input and output, including the functionprintf, which takes a string of characters insidedouble parentheses, and prints them in the com-mand line. Note: the newline character is given by“\n”.We are now ready to write our first pro-gram!

3.2 Procedure

1. Write a program in the default text editorwhich prints to screen a simple ”Hello, world!”statement.

2. Compile and run this program in terminal.

3.3 Example Code1// Example Code for Hello, world!2

3// Include standard library for input andoutput.

24

Page 25: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

4#include <stdio.h>5

6// Begin main program.7int main()8{9// Print text to terminal.10printf("Hello, world! \n");11// Finish program execution and return 0.12return(0);13}

25

Page 26: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

4 Evaluating a Simple Func-tion

4.1 Background

4.1.1 Data Types and Precision

There are several basic data types in C, each hav-ing a different amount of memory allocation asso-ciated with them. The three types we will employin this lab are integers (int), floating point num-bers (float), and long double precision numbers(long double). Similar to functions, variables ofa particular data type in C must be declared andassigned. This doesn’t have to, but usually hap-pens at once, for example a function might containthe lines

1int i;2i=5;

which declares the int t in line 1, and assigns thevalue 5 to it on line 2. Alternatively we can save

26

Page 27: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

lines by writing1int i=5;

which does both at once. Note: you cannot usea variable, (say i in this example) as an algebraicentity, it just is a name for a value. If you havenot assigned a value to the name, it will have someunpredictable value automatically assigned.

A variable declared within a function, is only de-clared within that function. When the functionfinishes evaluating the variable goes ‘out of scope’,meaning its allocated memory is cleared and thevariable needs to be pre-declared/assigned. We canalso define global constants at the beginning of ourfile. These are constants which are fixed through-out the program, and are visible to all functions.We do this by using the #define command at thepre-processor stage, for example

1#define X 5

could be written under your #include statements.X is now defined for all functions.

27

Page 28: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

A little more about these data types:

Integers can have either sign, and have a memoryallocation of 2 bytes if under ≃ 3×104, over whichthey take around 4 bytes. Integers have a maxi-mum value of ≃ 1×1010. Arithmetic with integerscan lead to decimal numbers. When assigning adecimal number to an integer variable, the num-ber will in general be rounded down to the nearestinteger.

A floating point number has a precision of 6digits and can be either sign. It has 4 bytes ofstorage assigned to it, and can be anywhere in therange 1.2× 10−38 → 1.2× 1038. It is important tobe aware that floating point arithmetic can lead torounding errors of order 10−7.

A long double precision number is like a floatbut has a precision of 80 bits and has between 12and 16 bytes of storage assigned to it dependingon its value. It can also be of either sign. Similarlyto floating point arithmetic, long double arithmeticcan lead to rounding errors of order 10−80.

28

Page 29: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Given the limited memory allocated to C data types,it is important to be careful that your functionsdo not rely on data which exceeds the size limita-tions above. If unavoidable (as is often the case inphysics applications!) make sure you re-scale yourdata so as not to exceed the limitations of yourdata type, but remember to scale your results backto the correct order of magnitude.

4.1.2 Operators

Functions are the stage, data types are the actors,but operators are the action...um...anyway, here area list of basic C arithmetic operators...

4.1.3 User Input

Also within stdio is the function scanf, whichreads data from user input and stores it in a vari-able of the appropriate type. It takes as functionparameters scanf("%x", reference_to_variable),where ‘x’ depends on the input data type (d for in-

29

Page 30: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Operator Name Descriptiona=b Assignment Assigns value b to

data type a.a +/- b Addition/Subtraction Adds/Subtracts a and

ba*b Multiplication Multiplies a and ba/b Division Divides a and ba+=b Addition Assignment a=a+ba-=b Subtraction Assign-

menta=a-b

a*=b Multiplication Assign-ment

a=a*b

a/=b Division Assignment a=a/b++a Prefix Increment Increases a by one

then returns aa++ Postfix Increment Returns a then in-

creases by one--a Prefix Decrement Decreases a by one

then returns aa-- Postfix Decrement Returns a then de-

creases by one

Table 3: List of basic C arithmetic operators.

30

Page 31: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

teger, f for float). The parameter ‘reference_to_variable’refers to the memory location of a declared vari-able. You don’t need to worry about this too muchyet, but the basic idea is that when a variable isdeclared, some amount of memory is put aside tostore it. This memory has a location in your sys-tem memory, and it is this location which is theinput to the function. The memory reference of avariable is recalled with the & operator, for example

1int i; // Allocates 2 bytes of memory to i.2i=5; // Assigns value of 5 to i.3i; // Returns 5.4&i; // Returns the location of the memory

used to store i.

We can also use the notation of scanf to intro-duce some new functionality to our printf func-tion, by including a variable assigned in our code inour output character string. Using similar syntaxto scanf, we can write printf("some string%x \n", variable), where as for scanf x is ofthe type ‘variable’, and is d for an integer or f for afloat (note that in this case ‘variable’ is the variableitself, not the memory location).

31

Page 32: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Lets put this together into an example. See section4.3 for an example program that takes two integersfrom user input, and adds them together, returningthe result

4.2 Procedure

1. Write a simple function quadratic(a,b,c,x),which returns y(x) = ax2 + bx + c.

2. Extend this program such that a, b, c and xare entered into the terminal by the user, andthe result y(x) is returned and displayed.

32

Page 33: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

4.3 Example Code1// Example Code for Evaluating a Simple

Function2// Author: Ahmad Galea3// Date: 01/03/20164

5#include <stdio.h>6

7int main()8{9// declare integers a and b.10int a, b;11// print user input prompt to terminal12printf("Enter integer value of a: \n");13// assign user input to integer a.14scanf("%d", &a);15// print user input prompt to terminal16printf("Enter integer value of b: \n");17// assign user input to integer b.18scanf("%d", &b);19// assign the sum of a and b to integer c.20int c = a+b;21// print c to terminal.22printf("a+b=%d \n",c);23

24return(0);

33

Page 34: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

25}

34

Page 35: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

5 Data Files and Plotting

5.1 Background

5.1.1 Exporting Data in C

Just as we used printf to write to the terminalin earlier sections, we can use the stdio functionfprintf to write to a file. First we must open anew file. This is done by first creating an object oftype FILE

1FILE *my_file;

don’t worry too much about the star precedingmy_file (for those with some background this istechnically a pointer to an object of type FILE, notthe object itself). We then use the function fopento open a new file and assign it to my_file,

1my_file = fopen("my_file.dat", "w");

where the "w" means the file has writing permis-sions. The other options can be seen in Table 4 We

35

Page 36: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Option Meaningr Open for readingw Open for writing (file need not exist)a Open for appending (file need not exist)

r+ Open for reading and writing, start at beginningw+ Open for reading and writing (overwrite file)a+ Open for reading and writing (append if file exists)

Table 4: fopen options.

can then write to the file using fprintf and thefollowing syntax

1int i = 1;2fprintf(my_file, "%d is and integer.", i);

and finally close the file with1fclose(my_file);

It is usually good procedure to use a file extensionwhich reflects the contents of a file, for example".dat" for data and ".txt" for text.

36

Page 37: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Just as as fprintf can be used to print data to afile (analogously to printf for printing to termi-nal), fscanf can be used to read data from a file(analogously to scanf user input). The syntax isthe similar to scanf, for example

1int j;2FILE * my_file;3my_file = fopen("my_file.dat", "r");4

5fscanf(my_file, "%d", &j);6

7fclose(my_file);

opens "my_file.dat" for reading, and assigns thefirst integer in the file to j.

5.1.2 Plotting Data

In these labs we will use the plotting program PG-PLOT, which is a multi platform library for plot-ting scientific data. It is loaded and used like anyother C library, by including the appropriate .h filein the relevant .c files, i.e. #include <cpgplot.h>.

37

Page 38: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Recall from Section 3.1.3 though that we also needto link the object files of the PGPLOT library withour programs object files in our executable in orderfor the PGPLOT functions to be defined as well asdeclared. Given that PGPLOT is installed in thesystem directory we can do this simply by enter-ing the command -lcpgplot before the -o whencompiling our program in terminal.

Below are some useful PGPLOT functions

cpgbeg is called to initiate PGPLOT and open theoutput device. It will prompt the user to supply thedevice name and type. It is called with

1cpgbeg(0, "/XWINDOW", 1,1);

Use “?” instead of “/XWINDOW” to bring up alist of display options.

cpgenv is called to specify the range of the axesand to draw the box which will contain the plot.Following this cpglab is called to label the axes,for example

1cpgenv(0.0, 5.0, 0.0, 10.0, 0, 1);

38

Page 39: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

2cpglab("(x)", "(y)", "PGPLOT Example 1: y(x)= 2x");

specifies axes x and y, run from 0-5, and 0-10 re-spectively.

cpgpt draws points in the plot. It takes C arrays ofx and y data values as input, along with the symbolused for the point, for example the following

1float y_values[4] = {2.0, 4.0, 6.0, 8.0};2float x_values[4] = {1.0, 2.0, 3.0, 4.0};3cpgpt(3, x_values, y_values, 9);

plots the first 3 elements of y_values, as a func-tion of x_values, using symbol number nine.

cpgline takes number of points, y_values, andx_values as inputs and plots a line between thepoints, for example

1float y_values[4] = {2.0, 4.0, 6.0, 8.0};2float x_values[4] = {1.0, 2.0, 3.0, 4.0};3cpgline(3, x_values, y_values);

creates the linear y(x) = 2x line plot.

39

Page 40: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Finally, calling cpgend(); terminates PGPlot prop-erly. We put all this together in the example below,using some further functions for prettier plots.

5.2 Procedure

1. Evaluate a simple function such as quadratic(a,b,c,x)over the range 1 ≤ x ≤ 5, with 5 equally-spaced data points.

2. Export a table of arguments and functionvalues to an external file such as ‘quadratic.dat’.

3. Read the data from ‘quadratic.dat’ and usePGPLOT to graph and print this data. (It isOK to copy the PGPLOT segment directlyform the example code. Read and under-stand the comments in the file. Try playingaround with the settings.)

5.3 Example Code

40

Page 41: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

1// Author: Julia McCoey2// Date: 01/03/20163// This program writes the function

'quadratic' to a data file "quadratic.dat".4

5

6#include <stdlib.h>7#include <stdio.h>8

9// Declare functions signatures.10// This provides the compiler the input

parameter and return types before itactually reads the function DEFINITIONdefined below main.

11float quadratic(float a, float b, float c,float x);

12

13// This the main program14

15int main()16{17

18FILE *dataFile; // File pointer for datafile

19float a = 2.0; // Arbitrary value a20float b = 3.0; // Arbitrary value b

41

Page 42: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

21float c = 5.0; // Arbitrary value c22

23dataFile=fopen("quadratic.dat", "w"); //Open the data file

24

25// Write 5 data points to file.26fprintf(dataFile, "%0.1f %0.1f\n", 1.0,

quadratic(a,b,c,1.0));27fprintf(dataFile, "%0.1f %0.1f\n", 2.0,

quadratic(a,b,c,2.0));28fprintf(dataFile, "%0.1f %0.1f\n", 3.0,

quadratic(a,b,c,3.0));29fprintf(dataFile, "%0.1f %0.1f\n", 4.0,

quadratic(a,b,c,4.0));30fprintf(dataFile, "%0.1f %0.1f\n", 5.0,

quadratic(a,b,c,5.0));31

32

33

34return 0;35}36

37

38//The 'quadratic' function is defined here:39

42

Page 43: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

40float quadratic(float a, float b, float c,float x)

41{42return (a*x*x)+(b*x)+c;43}

43

Page 44: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

6 Loops and Logic Statements

6.1 Background

6.1.1 If Function and Boolean Objects

Discrimination between variables is of fundamentalimportance in any program. The if function is thecore mode of assertion testing in C. Unlike regularfunctions, if can be inlined in any function, andhas the following syntax:

1if(test==true)2{3\\ Do stuff.4}

taking a Boolean (bool) type object as an argu-ment.

Boolean objects are defined such that they can haveeither true or false as their value. Table 5 showsa list of common comparison operators which resultin Boolean values.

44

Page 45: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Operator Namea == b Equal toa != b Not equal toa > b Greater thana < b Less thana >= b Greater than or equal

toa <= b Less than or equal to

Table 5: List of basic C comparison operators.Note that a and b can be of any type, includingbool.

45

Page 46: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Boolean values can be operated on using the oper-ators in Table 6.

Operator Name Descriptiona && b AND Returns true if a and

b are true.a || b OR Returns true if a or b

are true.!a NOT Returns true if a is

false.Table 6: List of basic C Boolean operators.

6.1.2 Loops in C

A loop is, in basic terms, an operation or seriesof operations, that is repeated while a particularassertion holds true. In flow chart language

46

Page 47: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Start

Test assertionDo operations

Stop

False

True

There are several loop types in C:

while loops are the simplest loop type. The whileloop has the same format as if, but will repeatuntil the Boolean argument becomes false, e.g.:

1while(test==true)2{3\\ Do stuff.4}

do while loops are the same as while loops, butthe assertion is tested after the operation rather

47

Page 48: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

than before, i.e.1do2{3\\ Do stuff.4}5while(test==true);

for loops perform a given operation while an iter-ator spans a range. They have this basic function-ality:

1int i=0;2while(i<i_max)3{4\\ Do stuff.5i++;6}

but expressed in a compact form. They have asimilar syntax to while loops, but take 3 argu-ments: the definition of the iterator, the Booleanvalue setting the upper bound, and the iteration ofthe value. For example

1for(int i=0; i<i_max; i++)2{

48

Page 49: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

3\\ Do stuff.4}

There is clearly some overlap in the functionalityof these loops, though usually one is the best toolfor the job. Be clear and try to think about yourapplication before choosing.

6.1.3 Series and Sequences

Series expressions are extremely useful in mathe-matics and physics, and are often the only solutionto a system of equations. By truncating a seriesat order N , we can find a numerical approxima-tion of the solution, which gets more accurate asN increases. Such is the case for the Gregory Se-ries expansion of π, which can be obtained fromMachins Formula

1

4π = 4 tan−1

(1

5

)− tan−1

(1

239

)(1)

and can be seen in Table 7, along with other validexpansions.

49

Page 50: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

Name DefinitionGregory 4

∑∞k=1

(−1)k+1

2k−1

Wallis 2∏N

k=1(2k)2

(2k−1)(2k+1)

Newton/Euler∑∞

k=0(k!)22k+1

(2k+1)!

Hayashi 4∑∞

k=1 arctan(

1F2k+1

)Table 7: Series expression for π

The Hayashi expansion uses the Fibonacci sequenceFn, given by

Fn = Fn−1 + Fn−2 (2)

where the sequence is seeded by the values F1 =F2 = 1.

Given their iterative nature, the numerical evalua-tion of series should be done with loops. Specifi-cally, given the incremental increase of the summedvariable, for loops are the most convenient to use.

50

Page 51: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

6.2 Procedure

1. Write a program which uses a loop to printintegers 1-10 in the terminal.

2. Write a loop which calculates the first 10 Fi-bonacci numbers, and print them to the ter-minal.

3. Write a function which uses a loop to calcu-late the series expression for π up to orderN , using the Euler Method.

4. Investigate the convergence of the formulaefor π in Table 7 (by comparison to its exactvalue) as a function of series truncation N,and produce a table of results. You can copythe methods directly from the example codefor this section.

5. Order these series formulae from most to leastconvergent.

6.3 Example Code

51

Page 52: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

1// Author: William Lawrie2// Date: 01/03/20163

4#include <stdio.h>5#include <stdlib.h>6#include <math.h>7

8#define NMAX 10009

10//Declare global variables:11

12//Declare functions:13double Gregory(int iteration);14double Wallis( int Iteration);15double Euler(int Iteration);16double Hayashi(int Iteration);17

18double factorial(double number);19double fibonaci(int number);20

21//The main part of the code. Functions thatapproximate pi

22//are called from here, in a loop thatdetermines the number

23//of iterations used to approximate.24int main()

52

Page 53: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

25{26///////////////////////27// Declare Variables //28///////////////////////29

30double pi_Gregory; //These keep track of theapproximation

31double pi_Wallis;32double pi_Euler;33double pi_Hayashi;34

35double del_Gregory; //These keep track ofthe error in the approximation

36double del_Wallis;37double del_Euler;38double del_Hayashi;39

40int N; // This is the variable that countsthe number of iterations

41// to use42

43//Here are the guts of the program. We feedin a number N,

44//which determines the number of iterationsto use in the

53

Page 54: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

45//relevant approximation. We loop overvalues of N between

46// 1 and 100 to get an idea of how quicklydifferent

47//approximations converge with number ofiterations.

48

49printf("N\tPi\t\tGregory\t\tDelGregory\n");50for( N = 0; N < NMAX; N++){51/*The values in the if statement below can

be changed at will, these are simply thevalues of interest

52for N number of iterations in the variousapproximations.*/

53if(N==1 || N==10 || N==100 || N==1000 ||N==NMAX-1){

54pi_Gregory = Gregory(N); //Calls theGregory approximation for N iterations

55del_Gregory = fabs(pi_Gregory - M_PI);//These calculate the error by takingthe absolute value

56printf("%d\t%4.6f\t%4.6f\t%4.6f\n",N,M_PI,pi_Gregory,del_Gregory);57}58}59

60

54

Page 55: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

61

62printf("N\tPi\t\tWallis\t\tDelWallis\n");63for( N = 0; N < NMAX; N++){64/*The values in the if statement below can

be changed at will, these are simply thevalues of interest

65for N number of iterations in the variousapproximations.*/

66if(N==1 || N==10 || N==100 || N==1000 ||N==NMAX-1){

67pi_Wallis = Wallis(N); //Calls theWallis approximation for N iterations

68del_Wallis = fabs(pi_Wallis - M_PI);//These calculate the error by takingthe absolute value

69printf("%d\t%4.6f\t%4.6f\t%4.6f\n",N,M_PI,pi_Wallis,del_Wallis);70}71}72

73

74printf("N\tPi\t\tHayashi\t\tDelHayashi\n");75for( N = 0; N < NMAX; N++){76if(N==1 || N==10 || N==50 || N==90){77pi_Hayashi = Hayashi(N); // '' ''

Hayashi '' '' ''

55

Page 56: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

78del_Hayashi = fabs(pi_Hayashi -M_PI);//the actual value of pi (M_PI)

79printf("%d\t%4.6f\t%4.6f\t%4.6f\n",N,M_PI,pi_Hayashi,del_Hayashi);80}81}82

83}84

85

86///////////////////////////////////////////87//// DEFINE FUNCTIONS: ////////////////////88///////////////////////////////////////////89

90//This is the Gregory approximation. It takesa number of iterations

91//over which to loop, thus improving upon theapproximation

92double Gregory(int iteration){93///////////////////////////94//Declare local variables//95///////////////////////////96double pi_new = 0.;97int i = 0;98double j = 0.;99///////////////////////////100

56

Page 57: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

101for(i=1;i<iteration+1;i++){102pi_new+=(pow(-1, i+1)/(2*i-1));103}104

105pi_new = 4.*pi_new;106return pi_new;107}108

109//This is the Wallis approximation. It takesa number of iterations

110//over which to loop, thus improving upon theapproximation. This

111//Approximation is given in full. Note thestructure, particularly the

112// way the approximation pi_new constantlyupdates itself inside the loop

113double Wallis(int iteration){114///////////////////////////115//Declare local variables//116///////////////////////////117

118double pi_new=1.; //Since the Wallis approxis a multiplicative sum,

119//We set the approximationinitially to 1.

120

57

Page 58: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

121int i = 0; //i is an integer, thatkeeps track of the number

122//of iterations being donein the loop

123

124double j = 0.; // j is a double type: itspurpose is to convert the

125//value of the integer 'i'as a double, so it can be

126//used in calculations. Thetake home message here is

127//that you should never tryto perform operations on

128//variables stored asdifferent types.

129

130///////////////////////////131

132

133//Begin the loop:134for(i=1;i<iteration+1;i++){135j = (double)i; //As mentioned before, we

convert the integer136//i into a double type and

store it as j137

58

Page 59: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

138pi_new = pi_new * (2.*j * 2.*j) / ((2.*j -1.)*(2.*j+1.));

139//This is Wallis approximationˆˆ140}141

142pi_new = 2.*pi_new; //Since the Wallisapprox technically approximates

143//pi/2 , we multiply outto get the final value

144return pi_new; //We return theapproximation to the main() section

145}146

147

148

149/*This is the Euler approximation. It takes anumber of iterations

150over which to loop, thus improving upon theapproximation.

151You'll need to write this and subsequent onesyourself.

152Some tips:153-Euler uses a conventional sum, so make

sure you set your154initial value to 0.

59

Page 60: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

155-to update your approximation inside aloop, you can either

156write pi_approx = pi_approx + next term157or pi_approx += next term158-Euler requires using a factorial

function, which is already159written for you below. just call

"factorial(k)" where k is a160double you want to calculate the factorial

of. don't try to calculate161the factorial of a negative number or

decimal.162*/163double Euler(int iteration){164///////////////////////////165//Declare local variables//166///////////////////////////167

168///////////////////////////169//Begin your for loop /////170///////////////////////////171

172////////////////////////////173//Return your approximation/174////////////////////////////175}

60

Page 61: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

176

177//This is the Hayashi approximation. It takesa number of iterations

178//over which to loop, thus improving upon theapproximation

179double Hayashi(int iteration){180///////////////////////////181//Declare local variables//182///////////////////////////183double pi_new = 0.;184int i = 0;185double j = 0.;186///////////////////////////187

188for(i=1;i<iteration+1;i++){189pi_new+=atan(1./fibonaci(2*i+1));190}191

192pi_new = 4.*pi_new;193return pi_new;194}195

196

197

198//Calculates the Factorial of the number 'n'199double factorial(double n){

61

Page 62: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

200///////////////////////////201//Declare local variables//202///////////////////////////203

204int i;205double fact = 1.;206///////////////////////////207

208if(n==0){209fact=1.;210}211else if(n<0){212fact = 1.;213printf("\nError! Negative input to

Factorial Function!\n");214}215else{216for(i = 0; i < n; i++){217fact = fact*(n-i);218}219}220return fact;221}222

223

224//Calculates the k'th fibonaci number

62

Page 63: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

225double fibonaci(int k){226///////////////////////////227//Declare local variables//228///////////////////////////229int i;230double fib2;231double fib1=1.; //F(1) = 1232double fib0=1.; //F(2) = 1233double j;234///////////////////////////235

236for(i=2;i<k;i++){ //i = 2 since k237fib2 = fib1 + fib0; //will be 3 or greater,238fib0 = fib1; //and F(1) and F(2) are239fib1 = fib2; //already defined240}241return fib2;242}

63

Page 64: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

7 Bonus Section: Special Func-tions and Recurrence Re-lations

7.1 Background

7.1.1 Series Representations of Bessel Func-tions

As an interesting application of numerical evalua-tion of series expansions, we will now look at thesolutions to Bessel’s equation, specifically, at BesselFunctions of the First Kind.

Bessel’s differential equation is given by

x2d2y

dx2+ x

dy

dx+ (x2 − n2)y = 0 (3)

It is a 2-dimensional wave equation, and has manyapplications in physics including the notable ex-amples: description of electromagnetic waves in acylindrical wave-guide, solutions to the radial SchrodingerEquation for a free particle, and modes of vibration

64

Page 65: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

on a circular drum. (refs)For integer n it has the series solutions

Jn(x) =

N∑l=0

(−1)l

22l+nl!(n + l)!x2l+n (4)

where N →∞.

7.2 Procedure (One Bonus Mark)

1. Use the series solution for Jn(x) of arbitraryinteger order n ≥ 1 to write a function bessj(n,x)

2. Generate and plot a data file bessjn.dat forthe zeroth- and first-order Bessel functionsJ0(x) and J1(x) between 0 ≤ x ≤ 10 with1000 data points, using each of N = {10, 50, 200}.

3. Repeat the above step for all Bessel functionsof the first kind, Jn(x), up to n = 6, using

65

Page 66: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

N = 200 terms in the series. (This will re-quire a nested loop). Plot the results.

66

Page 67: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

7.3 Example Code1// Example Code for Series Representation of

Bessel Functions2// Author: Chia-Ling Hsu3// Date: 23/02/20164

5#include <math.h>6#include <stdio.h>7#include <stdlib.h>8/*9This program needs to use long double for

the factorial function, since the resultwill

10be over the limit of double precision wheniterations is close to 200.

11*/12// Declare functions which will use later13long double factorial(int);14double bessel_n(int, double);15

16#define MAX_ARRAY 100117

18int main(void){19

20// Open a file21FILE *fp = fopen("bessel.dat","w");

67

Page 68: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

22// Check if the file is open, if not printout error message and quit the program

23if (fp == NULL)24{25printf("Error opening file!");26exit(1);27}28// Declare variable29double j0;30double j1;31double x = 0;32// Array for pgplot (pgplot only accepts

float type)33float j0p[MAX_ARRAY];34float j1p[MAX_ARRAY];35float xp[MAX_ARRAY];36

37// Loop for x iteration ( 0 <= x <= 10 )38int i;39for (i = 0; i < 1001; i++)40{41// Calculate x position for this step42x = 0.01*i;43xp[i] = x;44// Assign return values with the present x

position to j1, j2

68

Page 69: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

45j0 = bessel_n(0, x);46j1 = bessel_n(1, x);47// Fill in values to array48j0p[i] = j0;49j1p[i] = j1;50// Print out result to file51fprintf(fp, " %f %f\n", j0, j1);52

53}54// Close the file55fclose(fp);56return (0);57}58

59long double factorial(int n)60{61// Calculate factorial with given n62// NOTE: if n = 0, the function will skip

the loop and return the initial value63// Declare local variable for this function64long double fact = 1;65for (int c = 1; c <= n; c++)66{67fact = fact * c;68}69return fact;

69

Page 70: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

70}71

72double bessel_n(int n, double x)73{74// Declare local variables for this function75long double f_k = 0;76long double f_kn = 0;77int k;78double frac = 1;79double a_k = 0;80for (k = 0; k<=200; k++)81{82// Determine the factor of (-1)ˆk83if (k%2 == 0)84{85frac = 1;86}87else88{89frac = -1;90}91// Assign k! and (k+n)! for f_k and f_kn92f_k = factorial(k);93f_kn = factorial(k+n);94long double power = 1;

70

Page 71: 2nd Year Computational Physics Week 1 (standard): …part2/ONLINE/LABNOTES/Week_1_standard_large.pdf... cd Lab_1; touch Lab_1.c; gedit 1 ... tion of x_values, using symbol number nine

95// Calculate Exponential function with thebase x/2

96for (int i = 1; i<=2*k+n; i++)97{98// Iteratively increase the power of

exponential99power *= (0.5*x);100}101// Sum up each term in the series102a_k += (frac/(f_k*f_kn))*power;103}104// Return value105return a_k;106}

71