Computational Physics - Department of Physics

(Axel Boer) #1

40 2 Introduction to C++ and Fortran


precision problems discussed in the text. Write thereaftera program which implements this
algorithm.


2.5.The classical quadratic equationax^2 +bx+c=with solution


x=

(

−b±


b^2 − 4 ac

)

/ 2 a,

needs particular attention when 4 acis small relative tob^2. Find an algorithm which yields
stable results for all possible values ofa,bandc. Write thereafter a program and test the
results of your computations.


2.6.Write a Fortran program which reads a real numberxand computes the precision in bits
(using the functionDIGIT(x))for single and double precision, the smallest positive number
(usingTINY(x)), the largets positive number (using the functionHUGE(x)) and the number of
leading digits (using the functionPRECISION(x)). Try thereafter to find similar functionalities
in C++ and Python.


2.7.Write an algorithm and program which reads in a real numberxand finds the two nearest
machine numbersx−andx+, the corresponding relative errors and absolute errors.


2.8.Recurrence relations are extremely useful in representingfunctions, and form expedient
ways of representing important classes of functions used inthe Sciences. We will see two such
examples in the discussion below. One example of recurrencerelations appears in studies of
Fourier series, which enter studies of wave mechanics, be iteither in classical systems or
quantum mechanical ones. We may need to calculate in an efficient way sums like


F(x) =

N

n= 0

ancos(nx), (2.3)

where the coefficientsanare known numbers andxis the argument of the functionF(). If we
want to solve this problem right on, we could write a simple repetitive loop that multiplies
each of the cosines with its respective coefficientanlike


for( n=0; n < N; n++){
f += ancos(nx)
}
Even though this seems rather straightforward, it may actually yield a waste of computer
time ifNis large. The interesting point here is that through the three-term recurrence relation


cos(n− 1 )x− 2 cos(x)cos(nx)+cos(n+ 1 )x= 0 , (2.4)

we can express the entire finite Fourier series in terms ofcos(x)and two constants. The
essential device is to define a new sequence of coefficientsbnrecursively by


bn= ( 2 cos(x))bn− 1 −bn+ 2 +an n= 0 ,...N− 1 ,N, (2.5)

definingbN+ 1 =bN+ 2 +..···= 0 for alln>N, the upper limit. We can then determine all thebn
coefficients fromanand one evaluation of 2 cos(x). If we replaceanwithbnin the sum forF(x)
in Eq. (2.3) we obtain


F(x) = bN[cos(Nx)− 2 cos((N− 1 )x)cos(x)+cos((N− 2 )x)]+
bN− 1 [cos((N− 1 )x)− 2 cos((N− 2 )x)cos(x)+cos((N− 3 )x)]+...
b 2

[

cos( 2 x)− 2 cos^2 (x)+ 1

]

+b 1 [cos(x)− 2 cos(x)]+b 0. (2.6)
Free download pdf