Date post: | 07-Apr-2018 |
Category: |
Documents |
Upload: | xabihdez05 |
View: | 216 times |
Download: | 0 times |
of 25
8/3/2019 Fort Ran 3
1/25
11
FortranFortran --33
Arrays and FunctionsArrays and Functions
8/3/2019 Fort Ran 3
2/25
22
Arrays (matrices)Arrays (matrices)
Array elements are numbered 1, 2, 3,Array elements are numbered 1, 2, 3, and are stored in consecutive locations ofand are stored in consecutive locations ofmemory.memory.
A(1)
A(2)
A(3)
A(4)
8/3/2019 Fort Ran 3
3/25
33
Declaration of ArrayDeclaration of Array
REALREAL, DIMENSION (10) ::, DIMENSION (10) ::AA LOGICALLOGICAL, DIMENSION(5) ::, DIMENSION(5) :: TRUTHTRUTH
Character(lenCharacter(len
=15)=15)
, DIMENSION(100) ::, DIMENSION(100) ::
NAMESNAMES
Integer, dimension(10,10)Integer, dimension(10,10) :: B:: B
8/3/2019 Fort Ran 3
4/25
44
Declaration (contd.)Declaration (contd.)
One can use named constants inOne can use named constants indeclaration. This is useful in changingdeclaration. This is useful in changingmatrix sizes.matrix sizes.
Integer, Parameter :: dim=10Integer, Parameter :: dim=10
Real ::Real ::A(dimA(dim))
Integer ::Integer :: B(dim,dimB(dim,dim)) Real :: C(2*dim)Real :: C(2*dim)
8/3/2019 Fort Ran 3
5/25
55
Initialization of ArraysInitialization of Arrays An array element behaves like an ordinaryAn array element behaves like an ordinary
variable which has the same type as thevariable which has the same type as thedeclared array type.declared array type.
Array can be initialized by defining everyArray can be initialized by defining every
element :element :
Integer, Dimension (5) :: AInteger, Dimension (5) :: A
Do I=1,5Do I=1,5A(I) = 0A(I) = 0
End DoEnd Do
8/3/2019 Fort Ran 3
6/2566
Initialization of ArrayInitialization of Array
It is also possible to initialize array in theIt is also possible to initialize array in thedeclaration statement itselfdeclaration statement itself
Real, Dimension(5) :: A=(/1.,2.,3.,4.,5./)Real, Dimension(5) :: A=(/1.,2.,3.,4.,5./)
Initialization may be done with READInitialization may be done with READstatement from terminal or from a filestatement from terminal or from a file
Initialize through an implicit doInitialize through an implicit dointeger, dimension(5):: A=(/(i, i=1,5)/)integer, dimension(5):: A=(/(i, i=1,5)/)initializes A= 1,2,3,4,5initializes A= 1,2,3,4,5
8/3/2019 Fort Ran 3
7/25
77
Changing array rangeChanging array range
The default range of an array is from 1 to N.The default range of an array is from 1 to N.However, sometimes it is useful to change theHowever, sometimes it is useful to change the
range. For instance, if we want to store salesrange. For instance, if we want to store sales
figure of years from 2001 to 2007, it may befigure of years from 2001 to 2007, it may bebetter if we definedbetter if we defined
Real, Dimension(2001:2007) :: SalesReal, Dimension(2001:2007) :: Sales
Internally, computer will subtract 2000 from theInternally, computer will subtract 2000 from theargument to arrive at correct reference.argument to arrive at correct reference.
8/3/2019 Fort Ran 3
8/25
88
Matrix operationsMatrix operations
Fortran 90 allows whole matrix operationsFortran 90 allows whole matrix operations
between matrices of the same shape andbetween matrices of the same shape andoperations like addition, subtraction andoperations like addition, subtraction and
multiplication, division etc. will be done onmultiplication, division etc. will be done onelement to element basis,element to element basis, i.e. ani.e. anoperation C= A+B implies C (I , J)= A(I,J)operation C= A+B implies C (I , J)= A(I,J)
+B(I,J) or C= A*B implies C(I,J) =+B(I,J) or C= A*B implies C(I,J) =A(I,J)*B(I,J) andA(I,J)*B(I,J) and NOT usual matrixNOT usual matrixmultiplication.multiplication.
8/3/2019 Fort Ran 3
9/25
99
Bubble SortBubble Sort
Read N Data as an array of N numbersRead N Data as an array of N numbers For each I check if A(I) > A(J) for J= I+1For each I check if A(I) > A(J) for J= I+1to N. If yes, swap.to N. If yes, swap.
8/3/2019 Fort Ran 3
10/25
1010
Gauss Seidel MethodGauss Seidel Method
Read the coefficient matrix and theRead the coefficient matrix and ther.h.sr.h.s. of each equation. of each equation
The set of equations can be solved iteratively by writing the i-th equation asA
The solution of the i-th variable is
( ) /A
ii i ij j i
j i
i ij j i ii
j i
AX Y
X A X Y
X A X Y
=
+ =
= +
8/3/2019 Fort Ran 3
11/25
1111
GaussGauss--SeidelSeidel
The method converges if written inThe method converges if written indiagonally dominant formdiagonally dominant form
Give trial values of XGive trial values of Xii
Solve for each XSolve for each Xii iteratively.iteratively.
ij
j i
( ) ( ( ) sum(I)) / ( , ), wheresum(I)= A X I Y I A I I
=
8/3/2019 Fort Ran 3
12/25
8/3/2019 Fort Ran 3
13/25
1313
Subroutine structureSubroutine structure Similar to main program except for theSimilar to main program except for the
argument listargument list
Subroutine sub (Subroutine sub (argument listargument list))
Declaration sectionDeclaration sectionStatementsStatements
ReturnReturn
End subroutine subEnd subroutine sub
The variables in the argument list match theThe variables in the argument list match thetype and order in thetype and order in the DeclarationDeclaration in Subroutinein Subroutine
8/3/2019 Fort Ran 3
14/25
1414
How argument list is usedHow argument list is used Subroutine to calculate range of a projectileSubroutine to calculate range of a projectile
Subroutine RangeSubroutine Range ((init_velinit_vel, angle, time, range1), angle, time, range1)Implicit NoneImplicit None
Real INTENT(IN) ::Real INTENT(IN) :: init_velinit_vel, angle, angle
Real INTENT(OUT) :: range1, timeReal INTENT(OUT) :: range1, timeReal, parameter :: g=9.81Real, parameter :: g=9.81
Real, parameter :: pi=3.14159Real, parameter :: pi=3.14159
Real ::Real :: radian_angleradian_angle
radian_angleradian_angle = angle*pi/180.= angle*pi/180.Range1= (Range1= (init_velinit_vel)**2*sin(2*)**2*sin(2*radian_angle)/gradian_angle)/g
Time =2.*Time =2.* init_velinit_vel**sin(radian_angle)/gsin(radian_angle)/g
ReturnReturn
end subroutine Rangeend subroutine Range
2 sin2VR
g
=
8/3/2019 Fort Ran 3
15/25
1515
How a main program calls this subroutineHow a main program calls this subroutine
Program rangefinderProgram rangefinder
real :: u, t, theta, range2real :: u, t, theta, range2
Write(*,*)Write(*,*)Enter initial velocity u , angle ofEnter initial velocity u , angle of
projectionprojection in degrees and time tin degrees and time tRead(*,*)Read(*,*) u,t,thetau,t,theta
CallCall Range(uRange(u, theta, t, range2), theta, t, range2)Write(*,*)Write(*,*)Range=Range=, range,, range,timetime--, t, t
End program rangefinderEnd program rangefinder
8/3/2019 Fort Ran 3
16/25
1616
INTENT VariablesINTENT Variables
Dummy arguments in a subroutine canDummy arguments in a subroutine can
have INTENT attributehave INTENT attribute
INTENT(IN), INTENT(OUT),INTENT(IN), INTENT(OUT),
INTENT(INOUT)INTENT(INOUT) Intent attribute of each argument shouldIntent attribute of each argument should
be declared in the subroutine so thatbe declared in the subroutine so thataccidental tampering such arguments doaccidental tampering such arguments donot take place.not take place.
8/3/2019 Fort Ran 3
17/25
1717
Passing arrays as argument of a subroutinePassing arrays as argument of a subroutine
Calling argument passes a pointer to theCalling argument passes a pointer to thememory location of the array argument.memory location of the array argument.
There are several ways to pass on arrayThere are several ways to pass on arrayarguments. In this example we use dummyarguments. In this example we use dummyarguments where the arrays have the samearguments where the arrays have the sameshape as in the calling program.shape as in the calling program.
The main program calls a subroutineThe main program calls a subroutine matmultmatmult toto
do the matrix multiplication.do the matrix multiplication.
8/3/2019 Fort Ran 3
18/25
1818
Matrix Multiplication subroutineMatrix Multiplication subroutine
Program mainProgram main
Real, dimension (20,20) :: A,B,CReal, dimension (20,20) :: A,B,C
! 20X20 is the maximum size that the! 20X20 is the maximum size that the
multiplication is expected to be handled.multiplication is expected to be handled.Integer :: al, au,Integer :: al, au, blbl,, bubu
!these are actual dimensions of the!these are actual dimensions of thematrices A,B and that of product C, whichmatrices A,B and that of product C, whichwill be passed on. For multiplication au=will be passed on. For multiplication au=blbl
8/3/2019 Fort Ran 3
19/25
1919
Multiplication (Contd.)Multiplication (Contd.) Enter the matrix elements of A and BEnter the matrix elements of A and B
CallCall MatmultMatmult (A, B, al, au,(A, B, al, au, blbl,, bubu, C), C)Write CWrite C
Subroutine StructureSubroutine Structure ::
SubroutineSubroutine MatmultMatmult (A1,B1,al,au,bl,bu,C)(A1,B1,al,au,bl,bu,C)! The names of dummy arguments may or may not be! The names of dummy arguments may or may not bethe same as the real argument but their number and thethe same as the real argument but their number and theorder in which they appear must be identicalorder in which they appear must be identical
integer, intent (in) :: al, au,integer, intent (in) :: al, au, blbl,, bubureal,real, intent(inintent(in), dimension(20,20) :: A1,B1), dimension(20,20) :: A1,B1
real,real, intent(outintent(out), dimension(20,20) :: C), dimension(20,20) :: C
8/3/2019 Fort Ran 3
20/25
2020
Matrix multiplication (contd.)Matrix multiplication (contd.)
IF (au/=IF (au/=blbl) THEN) THENWrite(*,*)Write(*,*)The matrix is not conformableThe matrix is not conformable
stopstop
END IFEND IF
Carry out multiplication of matrices A1 andCarry out multiplication of matrices A1 and
B1 and store in result in CB1 and store in result in C
ReturnReturn
8/3/2019 Fort Ran 3
21/25
2121
FunctionFunction
Result is a single number, logical value aResult is a single number, logical value astring or an arraystring or an array
Intrinsic functions are built inIntrinsic functions are built in sin(xsin(x),),abs(xabs(x))
Here we talk about user defined functionsHere we talk about user defined functions
8/3/2019 Fort Ran 3
22/25
2222
FunctionsFunctions
Function definition should define the return type.Function definition should define the return type.This can be done in two ways :This can be done in two ways :
Integer functionInteger function myfunctionmyfunction (I, J)(I, J) OROR FunctionFunction myfunctionmyfunction (I,J)(I,J)
integer ::integer :: myfunctionmyfunction
8/3/2019 Fort Ran 3
23/25
2323
Program to calculate volume of a sphere,Program to calculate volume of a sphere,
given radius.given radius.
Main programMain program
Implicit noneImplicit none
Real :: radius, volumeReal :: radius, volume
Read(*,*) radiusRead(*,*) radiusWrite(*,*)Write(*,*)volume=volume=,, volume(radiusvolume(radius))
End MainEnd Main
The function program for volume would look as followsThe function program for volume would look as follows
8/3/2019 Fort Ran 3
24/25
2424
Subroutine VolumeSubroutine VolumeReal functionReal function volume(Rvolume(R))
! R is a dummy argument corresponding to radius in main.! R is a dummy argument corresponding to radius in main.implicit noneimplicit none
Real,Real, intent(inintent(in) :: R) :: R
Real, parameter :: pi=3.14159Real, parameter :: pi=3.14159If (r
8/3/2019 Fort Ran 3
25/25
2525
RecursionRecursion A function can call itself recursivelyA function can call itself recursively For instance n! = n*(nFor instance n! = n*(n--1)!1)!Recursive function factorial (n)Recursive function factorial (n) Result(facResult(fac))! Note the return value is in Result,! Note the return value is in Result, facfac is the result returnedis the result returned
Integer,Integer, intent(inintent(in) :: n) :: n
Integer ::Integer :: facfac
If (n==0) thenIf (n==0) then
FacFac=1=1
ElseElse
FacFac= n*factorial(n= n*factorial(n--1)1)
End ifEnd if
End Function FactorialEnd Function Factorial