Computational Physics - Department of Physics

(Axel Boer) #1

16 2 Introduction to C++ and Fortran


C++: short int age_of_participant;


Note that the (KIND=2)can be written as (2). Normally however, we will for Fortran pro-
grams just use the 4 bytes default assignment INTEGER.
In the above examples one bit is used to store the sign of the variable age_of_participant
and the other 15 bits are used to store the number, which then may range from zero to
215 − 1 = 32767. This should definitely suffice for human lifespans. On the other hand, if we
were to classify known fossiles by age we may need


Fortran: INTEGER (4) :: age_of_fossile
C++: int age_of_fossile;


Again one bit is used to store the sign of the variable age_of_fossile and the other 31 bits are
used to store the number which then may range from zero to 231 − 1 = 2. 147. 483. 647. In order
to give you a feeling how integer numbers are represented in the computer, think first of the
decimal representation of the number 417


417 = 4 × 102 + 1 × 101 + 7 × 100 ,

which in binary representation becomes


417 =an 2 n+an− 12 n−^1 +an− 22 n−^2 +···+a 020 ,

where the coefficientsakwithk= 0 ,...,nare zero or one. They can be calculated through
successive division by 2 and using the remainder in each division to determine the numbers
antoa 0. A given integer in binary notation is then written as


an 2 n+an− 12 n−^1 +an− 22 n−^2 +···+a 020.

In binary notation we have thus


( 417 ) 10 = ( 110100001 ) 2 ,

since we have


( 110100001 ) 2 = 1 × 28 + 1 × 27 + 0 × 26 + 1 × 25 + 0 × 24 + 0 × 23 + 0 × 22 + 0 × 22 + 0 × 21 + 1 × 20.

To see this, we have performed the following divisions by 2


417/2=208 remainder 1 coefficient of 20 is 1
208/2=104 remainder 0 coefficient of 21 is 0
104/2=52 remainder 0 coefficient of 22 is 0
52/2=26 remainder 0 coefficient of 23 is 0
26/2=13 remainder 0 coefficient of 24 is 0
13/2= 6 remainder 1 coefficient of 25 is 1
6/2= 3 remainder 0 coefficient of 26 is 0
3/2= 1 remainder 1 coefficient of 27 is 1
1/2= 0 remainder 1 coefficient of 28 is 1

We see that nine bits are sufficient to represent 417. Normally we end up using 32 bits as
default for integers, meaning that our number reads


( 417 ) 10 = ( 00000000000000000000000110100001 ) 2 ,

A simple program which performs these operations is listed below. Here we employ the
modulus operation (with division by 2), which in C++ is givenby thea%2operator. In Fortran
we would call the function MOD(a,2)in order to obtain the remainder of a division by 2.

Free download pdf