Computational Physics - Department of Physics

(Axel Boer) #1

18 2 Introduction to C++ and Fortran


cin >> int2;
int1 = (int) pow(2., (double) int2);
cout <<" 2^N2^N = "<< int1int1 <<"\n";
int3 = int1 - 1;
cout <<" 2^N(2^N - 1) = "<< int1int3 <<"\n";
cout <<" 2^N- 1 = "<< int3 <<"\n";
return0;
}
// End: program main()


If we run this code with an exponentN= 32 , we obtain the following output


2^N *2^N = 0
2^N*(2^N - 1) = -2147483648
2^N- 1 = 2147483647

We notice that 264 exceeds the limit for integer numbers with 32 bits. The program returns
0. This can be dangerous, since the results from the operation 2 N( 2 Nāˆ’ 1 )is obviously wrong.
One possibility to avoid such cases is to add compilation options which flag if an overflow or
underflow is reached.


2.2.1 Fortran codes


The corresponding Fortran code is


http://folk.uio.no/mhjensen/compphys/programs/chapter02/Fortran/program2.f90
PROGRAMbinary_integer
IMPLICITNONE
INTEGERi,number, terms(0:31)! storage of a0, a1, etc, up to 32 bits,
! note array length running from 0:31. Fortran allows negative indexes as well.


WRITE(,)'Give a number to transform to binary notation'
READ(,)number
! Initialise the terms a0, a1 etc
terms = 0
! Fortran takes only integer loop variables
DOi=0, 31
terms(i) = MOD(number,2)! Modulus function in Fortran
number=number/2
ENDDO
! write out results
WRITE(,)'Binary representation '
DOi=0, 31
WRITE(,)' Term nr and value', i, terms(i)
ENDDO


END PROGRAMbinary_integer


and


http://folk.uio.no/mhjensen/compphys/programs/chapter02/Fortran/program3.f90
PROGRAMinteger_exp
IMPLICITNONE
INTEGER:: int1, int2, int3
! This is the begin of a comment line in Fortran 90

Free download pdf