Computational Physics
numerical methods with C++ (and UNIX)2018-19
Fernando BaraoInstituto Superior Tecnico, Dep. Fisica
email: [email protected]
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (1)
C++ variables✔ Global variables
They are defined outside the main function and user defined functions.They are available to the program and user functions.
1 i n t n ; / / g l oba l v a r i a b l e2 double f a c t o r i a l ( ) ; / / f u n c t i o n p ro to t yp i ng3 i n t main ( ) {4 for ( n=0; n<=20; n++)5 { p r i n t f ( " f a c t o r i a l =%12.3e \ n " ,n , f a c t o r i a l ( ) ) ; }6 return 0;7 }
✔ Local variablesVariables defined inside the functions and private to them or within C++code blocks { ... }.
The return from the function frees the local variable locations (lost)!
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (2)
C++ variables (cont.)✔ Static variables
Variables defined inside the functions can be declared as static andtherefore their value is preserved between calls to the function.Mechanism that can be used to run code only once.
1 double F( i n t n ) { / / f u n c t i o n code2 s t a t i c i n t i n i t f l a g = 0;3 i f ( ! i n i t f l a g ) {4 do i n i t i a l i z a t i o n statements ;5 i n i t f l a g ++;6 } / / j u s t run once7 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (3)
C++ functions arguments✔ Passing by value
A copy of the variable is made and passed to the function. Anymodification of the variable inside the function will be local and lostat return!
1 / / The v a r i a b l e n i s passed by value to the f a c t o r i a l ( )f u n c t i o n
23 double f a c t o r i a l ( i n t ) ; / / f u n c t i o n p ro to t yp i ng4 i n t main ( ) {5 i n t n=10; / / v a r i a b l e to be passed6 double a = f a c t o r i a l ( n ) ;7 return 0;8 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (4)
C++ functions arguments (cont.)✔ Passing by pointer
The memory address of the variable is passed to the function andtherefore the variable contents inside the function can be modified.
1 / / The r e s u l t o f the f a c t o r i a l ( ) f u n c t i o n i s passed to the2 / / main program through a p o i n t e r to a double ;3 / / the double i s i n i t i a l i z e d i n the main program .45 void f a c t o r i a l ( int , double∗ ) ; / / p o i n t e r to double i s passed6 i n t main ( ) {7 i n t n=10; double d = 1 . ;8 f a c t o r i a l ( n , &d ) ;9 return 0;
10 }11 void f a c t o r i a l ( i n t n , double∗ pd ) {12 double f a c t = ∗pd ;13 for ( i n t count=n ; count > 0 ; −−count ) f a c t ∗= ( double ) count ;14 / /YOU SHOULD TRY IT ! ! ! MISTAKE?15 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (5)
C++ functions arguments (cont.)✔ Passing by reference
Similar to the pointer passing but more symbolic!
1 / / The r e s u l t o f the f a c t o r i a l ( ) f u n c t i o n i s passed to the main2 / / program through a re ference to the address o f a v a r i a b l e (
p o i n t e r ) ;3 / / the double i s i n i t i a l i z e d i n the main program .45 void f a c t o r i a l ( int , double&) ; / / double address re ference i s
passed6 i n t main ( ) {7 i n t n=10; double d = 1 . ;8 f a c t o r i a l ( n , d ) ;9 return 0;
10 }11 void f a c t o r i a l ( i n t n , double& f a c t ) {12 for ( i n t count=n ; count > 0 ; −−count ) f a c t ∗= ( double ) count ;13 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (6)
C++ functions arguments (cont.)✔ Passing arrays
Unlike scalar variables, arrays cannot be passed by value. Reference orpointer have to be used.
1 / / A one dimensional a r ray con ta in ing values o f i n t ege rs2 / / i s passed to f u n c t i o n f a c t o r i a l ( )34 void f a c t o r i a l ( int , i n t ∗ , double∗ ) ; / / passing p o i n t e r5 i n t main ( ) {6 i n t v i [ 4 ] = { 1 0 , 8 , 4 , 1 0 } ; / / dim−4 ar ray i n i t i a l i z e d7 double vr [ 4 ] = { 0 . } ;8 f a c t o r i a l (4 , v i , v r ) ;9 return 0;
10 }11 void f a c t o r i a l ( i n t n , i n t ∗ v i , double∗ vr ) {12 for ( i n t i =0; i <n ; i ++) {13 for ( i n t count= v i [ i ] ; count > 0 ; −−count ) v r [ i ] ∗= ( double )
count ;14 }15 } / / MISTAKE on the FACTORIAL CALCULATION???
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (7)
C++ functions arguments (cont.)✔ default argument value
In the prototyping of the function a default value to arguments can bedefined.
1 / / A one dimensional a r ray con ta in ing values o f i n t ege rs2 / / i s passed to f u n c t i o n f a c t o r i a l ( )34 void f a c t o r i a l ( i n t ∗p=NULL, double ∗pd=NULL, i n t n=4) ;5 i n t main ( ) {6 i n t v i [4 ]= {10 ,12 ,15 ,22 } ; / / dim−4 ar ray i n i t i a l i z e d7 double vr [ 4 ] = { 0 . } ;89 f a c t o r i a l ( ) ; / / by de fau l t , the value n=4 w i l l be passed
10 / / and the NULL po in te r s1112 f a c t o r i a l ( v i , v r ) ; / / the value n=4 w i l l be passed by d e f a u l t13 / / and the v a l i d po in te r s1415 return 0;16 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (8)
C++ function overloading and recursivecalling
✔ function overloading: Excepting the main() function, two entirelydifferent functions are allowed to have the same name, provided theyhave distinct list of arguments
1 / / two same name f u n c t i o n s p ro to t yp i ng2 double f a c t o r i a l ( i n t ) ;3 void f a c t o r i a l ( i n t ∗ , double∗ , i n t ) ;45 i n t main ( ) {6 i n t n=10; / / v a r i a b l e to be passed7 double a = f a c t o r i a l ( n ) ;89 i n t v i [ 2 ] = {5 , 7 } ;
10 double vr [ 2 ] = { } ; / / i n i t to zeros11 f a c t o r i a l ( v i , vr , 2) ;1213 return 0;14 }
✔ recursive calling: C++ functions are allowed to call themselvesComputational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (9)
C++ preprocessor directives
✔ A statement following the # character in a C++ code is a compiler ofpreprocessor directive
#include < f ile > includes file at this location ofthe code
#define VAR 100 the preprocessor will replacethe variable VAR by 100
#undef VAR undefine VAR
#define getmax(a,b) a > b?a : b the preprocessor will replacethe symbolic code getmax() bythe logical condition
#ifdef VAR ... #endif conditional inclusions depen-ding if VAR is defined
#ifndef VAR ... #endif conditional inclusions depen-ding if VAR is not defined
#if ... #elif ... #else ... #endif conditional inclusions
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (10)
C++ header filesWhen writing a program you can divide it into three parts:
✔ a header file containing the structure declarations andprototypes for functions that can be used by thosestructures➜ function prototypes➜ symbolic constants defined using #define or const➜ structure declarations➜ class declarations➜ inline functions
✔ a source code file that contains the code for thestructure-related functions
✔ a main programComputational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (11)
C++ header files (cont.)✔ A set of prototyping functions are already defined in header files *.h and can be
included through the preprocessor directive #include <header file>
✔ The #include statement asks the preprocessor to attach at the location of thestatement a copy of the header file
✔ The C++ preprocessor runs as part of the compilation process
files obs
iostream, cstdio, fstream, iomanip, iostream, strstream input/output
cmath, complex, cstdlib, numeric, valarray mathematical
string, cstring, cstdlib strings
algorithms STL algorithms
vector, list, map, queue, set, stack STL containers
iterators STL iterators
ctime, functional, memory, utility general
cfloat, climits, csignal, ctime, cstdlib, exception language
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (12)
C++ program arguments1 /∗2 The main ( ) f u n c t i o n may o p t i o n a l l y have arguments which a l low parameters to be
3 passed to the program from the opera t ing system
4 ∗ /
5
6 # inc lude <cs td io > / / p r i n t f
7 # inc lude < c s t d l i b > / / a to i , a t o f
8
9 i n t main ( i n t argc , char ∗argv [ ] ) {
10
11 / / r e t r i e v i n g charac te r ar rays
12 for ( i n t i =0; i <argc ; i ++) { / / argc= number o f arguments + 1 ( program name)
13 p r i n t f ( " argument number %d , %s \ n " , i , argv [ i ] ) ;
14 }
15
16 / / r e t r i e v i n g argument numbers
17 for ( i n t i =1; i <argc ; i ++) { / / argc= number o f arguments + 1 ( program name)
18 double a = a t o f ( argv [ i ] ) ;
19 p r i n t f ( " argument number %d , %10.2 f \ n " , i , a ) ;
20 }
21
22 return 0;
23 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (13)
C++ timing
✔ The header file time.h defines a number of libraryfunctions which can be used to assess how much CPUtime a C++ program consumes during execution
✔ A call to the function clock() will return the amount of CPUtime used so far
✔ To normalize the time to seconds the returned numbershall be divided by the variable CLOCKS _PER_SEC,defined inside time.h
✔ Next example computes time per operation inmicroseconds spent in calculating x4, in a direct way andthrough the pow() function
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (14)
C++ timing (cont.)1 #include <ctime > / / c lock ( )
2 #include <cmath> / / pow ( )
3 #include <iostream > / / cout
4 using namespace std ;
5 #define N 1000000
6
7 i n t main ( ) {
8 double a=12345678967598.0 , b ; / / v a r i a b l e d e c l a r a t i o n
9
10 / / compute t ime spent on power to the f o u r t h the double
11 c lock_ t t ime1 = c lock ( ) ;
12 for ( i n t i =0; i <N; i ++) b=a∗a∗a∗a ;
13 c lock_ t t ime2 = c lock ( ) ;
14 double dtime1 = ( double ) ( t ime2−t ime1 ) / ( double )CLOCKS_PER_SEC;
15
16 / / . . . using pow
17 c lock_ t t ime1 = c lock ( ) ;
18 for ( i n t i =0; i <N; i ++) b=pow( a , 4 . ) ;
19 c lock_ t t ime2 = c lock ( ) ;
20 double dtime2 = ( double ) ( t ime2−t ime1 ) / ( double )CLOCKS_PER_SEC;
21
22 cout << dtime1 << ‘ ‘ | ‘ ‘ << dtime2 << endl ;
23 return 0;
24 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (15)
C++ random numbers✔ Some calculations require the use of random numbers like the
Monte-Carlo calculations
✔ The system header file stdlib.h provides the function rand() thatreturns a random integer (fairly good approximation) in the range[0, RAND_MAX]
✔ The sequence seed can be fixed through a call to srand(int) renderingtherefore the random sequences repeatableby default, rand() is seeded with the value 1
✔ To generate independent sequences a common practice is to use thecurrent UNIX time (number of seconds elapsed since January 1st,1970)time(NULL) returns an integer
✔ The next example produces a sequence of 105 values between 0 and 1
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (16)
C++ random numbers (cont.)1 #include <ctime > / / t ime ( )
2 #include < c s t d l i b > / / rand ( )
3 #include <iostream > / / cout
4 using namespace std ;
5
6 i n t main ( ) {
7 / / se t random seed
8 srand ( t ime (NULL) ) ;
9
10 / / generate random values and compute mean and var iance
11 double sum= 0 . ;
12 double var = 0 . ;
13 for ( i n t i =0; i <100000; i ++) {
14 double x = ( double ) rand ( ) / ( double )RAND_MAX;
15 sum += x ;
16 var += ( x−0.5)∗(x−0.5) ;
17 }
18 double mean = x /100000. ;
19 var /= 100000.;
20
21 cout << mean << ‘ ‘ | ‘ ‘ << var << " ( expected var iance = 1/12) WHY??? ’ ’ << endl ;
22 r e t u r n 0 ;
23 }
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (17)
C++ complex numbers✔ complex numbers are implemented in C++ through the complex class
#include <complex> //C++ standard library
using namespace std;
int main() {
complex<double> Z(2.5, 4.0);
double Zmod = abs(Z);
double Zr = z.real();
double Zi = z.imag();
complex<double> Zc = conj(Z);
}
✔ C++ example of using complex class: Tcomplex.C
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (18)
C++ Input / Output✔ The iostream library allow us to enter data from keyboard and display data on
monitor
1 #include <iostream >2 using namespace std ;34 . . .5 / / read severa l r e a l values from the keyboard6 f l o a t a , b , . . . ;7 c in >> a >> b >> . . . ;89 / / read a s t r i n g from keyboard ( no blank spaces )
10 s t r i n g s ;11 c in >> s ;1213 / / read a f u l l l i n e ( i n c l u d i n g blank spaces )14 s t r i n g s ;15 g e t l i n e ( c in , s ) ;1617 / / ou tput l i n e18 cout << s << endl ;19 cout << s << " \ n " ; / / s i m i l a r to prev ious l i n e
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (19)
C++ Input / Output (cont.)✔ The fstream library allow us read from and write to files
1 / / read from f i l e23 #include <fstream >4 using namespace std ;56 . . .7 / / dec lare i n p u t f i l e stream and open " f i lename . dat " f i l e8 i f s t r eam F ;9 F . open ( " f i lename . dat " ) ; / / s h o r t l y could be : i f s t r eam F ( " f i lename . dat " ) ;
1011 / / read f i l e values12 i n t i =0;13 double a [ 1 0 ] ;14 while (F>>a [ i ] && i <10) { / / l o g i c a l t r ue i f reading OK15 cout << i << " " << a [ i ] << endl ;16 i ++;17 }1819 F . c lose ( ) ; / / c lose f i l e
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (20)
C++ Input / Output (cont.)✔ The fstream library allow us read from and write to files
1 / / w r i t e to f i l e23 #include <fstream >4 using namespace std ;56 . . .7 / / dec lare output f i l e stream and open " f i lename . dat " f i l e8 ofstream F( " f i lename . dat " ) ;9
10 / / ou tput values read before to f i l e11 i n t i =0;12 double a [ 1 0 ] ;13 while ( i <10) { / / l o g i c a l t r ue i f reading OK14 cout << i << " " << a [ i ] << endl ;15 F << a [ i ] ;16 i ++;17 }1819 F . c lose ( ) ; / / c lose f i l e
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (21)
C++ Input / Output (cont.)✔ The fstream library allow us read from and write to files
1 / / read and w r i t e to f i l e23 #include <fstream >4 using namespace std ;56 . . .7 / / dec lare output f i l e stream and open " f i lename . dat " f i l e8 fs t ream F( " f i lename . dat " , i os : : i n | i os : : out | i os : : app ) ; / / app= i f f i l e
e x i s t s w r i t e a t end9
10 / / ou tput values read before to f i l e11 i n t i =0;12 double a [ 1 0 ] ;13 while ( i <10) { / / l o g i c a l t r ue i f reading OK14 cout << i << " " << a [ i ] << endl ;15 F << a [ i ] ;16 i ++;17 }1819 F . c lose ( ) ; / / c lose f i l e
Computational Physics 2018-19 (Phys Dep IST, Lisbon) Fernando Barao (22)
22-1