Introduction to Fortranfluid.web.nitech.ac.jp/Gotoh_Home_page/Edu/Under...line : 1 line can be...
Transcript of Introduction to Fortranfluid.web.nitech.ac.jp/Gotoh_Home_page/Edu/Under...line : 1 line can be...
Nagoya Institute of Technology
Nagoya Institute of Technology
Graduate School of Engineering
Department of Scientific and Engineering Simulation
T. Gotoh
Introduction to Fortran
Nagoya Institute of Technology
Fortran (FORmula TRANslator)
Advanced programming language for numerical computation
developed by IBM (1950)
・ Oriented for mathematical operation
(matrix algebra, complex number, various Built-in functions)
・ Better performance than C, C++ for the numerical computation
・ Many mathematical library
・ Easiness for parallelization
・ High performance on super computer
Nagoya Institute of Technology
History
Fortran66 Born as the first programming language
Fortran77 Fixed form, many mathematical libaries developed
(vector type super computer)
Fortran90 Major change, free form, structuring
enhanced parallel operation
(parallel type super computer)
Fortran95 Minor change
Fortran2003 Refinement (including Fortran90/95)
Fortran2008 Standardization of parallel operation
(massive scalar parallel machine)
Nagoya Institute of Technology
Simple example (free form)
! Computation of three kinds of averages comment
Program Example_1_1 program sentence (not necessary)
Real:: a,b,av1,av2,av3 declaration of type
(all variables need type declaration)
print *, ‘enter two numbers’ output to the standard device (*: display)
Read *, a,b Read data (*: Keyboard)
av1=(a+b)/2.d0 computation
av2=(a*b)**0.5
av3=2.0/(1.0/a+1.0/b)
print *, av1,av2,av3 write data on the display
End Program Example_1_1 End
Nagoya Institute of Technology
Process
1. Write program by using an editor application
Save it as test.f90 (.f90, fortran90 free format)
2. Compile program
Use command prompt
Type g95 test.f90
3. Execute
Type as a.exe
Fortran getting started
Nagoya Institute of Technology
Change directory
Compile
execute
Nagoya Institute of Technology
Fortran grammar
1
Nagoya Institute of Technology
Character
alphabet : A-Z (non case sensitive, keep easiness of reading )
number : 0~9
underline : _
special : (space) = + - * / ( ) , . ’ : ! ” % & ; < > ?$
Writing
fixed form: begin with 7th column and end up to 72
file name is sample.for (Windows) sample.f (Unix)
free form: begin at any position
file name is sample.f90
Nagoya Institute of Technology
Free form
line : 1 line can be started at any column and should be shorter than 132 character
; semicolon allows to add executable statements after this in the same line
x=1.d0 ; y=2.d0 ; z=3.d0
comment : part of line after ! becomes comment (even in the middle of line)
! This is an example
y=sin(x) ! Sine function
continuation : to continue to the next line, add & at the end of the previous line,
y= 1.0+ 2.0*x*x+ cos(x) &
+ 0.5*sin (2.0*x)
space: space can be inserted exept executable statements
○ endif ○ end if
○ forall × for all
Nagoya Institute of Technology
Program main
…..
call time_advance (u1,u2,u3)
…..
End program main
Subroutine time_advance (u1,u2,u3)
……
return
End
main program
sub program
Program unit Example
Program unit
Program structure
Program <program name> (can be omitted)
…….
…….
end <Program program name>
Kind of sub program name of subprogram
(necessary)
…….
…….
end <Kind of sub program name of subprogram >
Nagoya Institute of Technology
Kind of statements
declaration statetment : set memory size, non executable statement
real*8 :: a,b,c ; integer :: i,j,k
dimension (10,10):: array
executable statement : control computation and flow of processes
do i= 1,10
a(i)=2*i
if (i > 3) exit
end do
Order of statements
program unit name (program, subroutine, function)
declaration (type statement, common statement)
data
executable statement
contains
end (need for each program unit)
Nagoya Institute of Technology
Name of program unit and variables begin with alphabets and less than 31 letters
vel1, vel2, stream_function, Potential_1
random_number_generator
Variables and constants variables : quantity whose value chanegs as program proceeds
scalar, vector, matrix
integer, real single, double real, complex …
constants: quantity uncanged under processes integer constat, 4 bytes (8×4=32 bit) -231=-2147483648 ~ 231-1= 2147483647 real consant, single precision 4 bytes, double precision 8 bytes decimal form 3.141592 floating form 7.199847e-12 complex constant, set of two real numbers 2+3i=(2.e0, 3.e0) logical constant, 4 bytes .true. .false. character constant, 1 character (alphabets) 1 byte 1 character (Japanese) 2 bytes
Nagoya Institute of Technology
Loop label
loop1 : do j=1,n2
loop2 : do i=1,n1
…………..
…………..
end do: loop2
end do: loop1
Effective when the operation part is long
Nagoya Institute of Technology
Substitution
variable = variable, constant, formula
= to substitute the value of the right hand side
Program summation
integer :: sum,i
sum=0
do i=1,100
sum = sum+1 algorithm for summation
end do
print *, sum
end
Numerical computation
Nagoya Institute of Technology
Arithmetic operation
additon + a + b
subtraction – a - b
multiplication * a * b
division / a / b
power ** x**3 = x*x*x
Order of arithmetic operation
addition, subtraction < product, division < exponent
compute from left to right. When ( ) exits, () must be computed first.
x+y*z= x+(y*z)
x/y/z= (x/y)/z
x*y**2= x*(y**2)
x**y**2=x**(y**2)
Nagoya Institute of Technology
Output of characters
print *, ` what you write‘
real, parameter :: pi=3.14159265
real:: r,s
read *,r
s=pi*r*r
print *, `radius, area`, r, s
end
Oder of operation
From top to bottom
integer :: s
s=10
s=s+1; print *, s
s=s+1; print *, s
s=s+1; print *, s
end
Nagoya Institute of Technology
Exercise 1
read positive real x and positive integer n, compute x**n and x**(1.e0/n),
and print them
Exercise 2
Find Fahreheit from Celcius
F=1.8C +32.0
Exercise 3
Compute BMI from weight L (m) and W (kg).
BMI = w / L2
Nagoya Institute of Technology
! ex1
real:: x,xn,xn1
integer:: n
read *,x,n
x1=x**n
xn1=x**(1.e0/n)
print *,x,n,x1,xn1
end
! ex2
real::c,f
read *,c
f=1.8*c +32.0
print *,c,f
end
! ex3
real::L,w,bmi
print *,'Enter W and L'
read *,w,L
bmi=w/(L**2)
print *,'weight[kg]=',w,', Hight[m]=',L, ', BMI=',bmi
end
Answer Program
Nagoya Institute of Technology
2
Nagoya Institute of Technology
Control of flow
if, stop, goto, case
1 If
if ( Iogical statement, relation, logical algebra) excutable statement
when the value of ( ) is ture, the statetment is executed.
Integer n, s
n=32
s=1
if ( n>=10 ) s=2*s +1
2 stop stop <‘message’>
stop here (with message) without jump to the end statement
Integer n
if ( n<0 ) stop ‘n must be positive integer’
Nagoya Institute of Technology
3. goto
goto number (go to number)
jump to the line with specifiled numer
Integer:: n, s, k, sum
k=0; s=0; sum=0
10 print *,’enter students mark (quit, if negative integer)‘
read *, n
if ( n<0 ) go to 999
s=s+1
sum=sum+n
if ( n >=60) k=k+1
go to 10
999 print *,‘Total and No . of students passed this exam. =‘,s,k
print *,’Average of score =‘, sum/s
end
Nagoya Institute of Technology
Relational operator
> .gt. greater than
< .lt. smaller than
<= .le. smaller than or equal
== .eq. equal to
/= .ne. not equal to
if ( n+m > 0 ), if ( a < 4.5 )
types of valiables in both side in relational operator should be the same
Logical operator
.not. logical negation
.and. logical product
.or. logocal sum
.eqv. logical equaivalence
.neqv. logical nonequivalence
n=0 or 1 (n==0).or.(n==1)
0 < k < 8 (0<k).and.(k<8)
x=y=z (x==y).and.(y==z)
Nagoya Institute of Technology
Priority of operators
.neqv. .eqv. < .or. < .and. < .not.
< relational operator < arithmetic operator
use of ( ) is recommended
operations of the same priority should be made from the left
x+y > 1.0e0 (x+y) > 1.e0
( x < 3.14 ) .or. ( z < sqrt(2.e0) )
Nagoya Institute of Technology
if statement with more funcions label1: if ( logical statement ) then
………
executable statements
………
endif <labbel1> (use the label in pair)
if (logical statement ) then
………
else
………
endif
if (logical statement_1 ) then
………
else if ( logical statement_2 ) then
………
else
………
endif
1. no limitation on the number of branches
2. multiple if nests can be used
3. no enter into if nest is allowed
No enter exit allowed
Nagoya Institute of Technology
block1: if (logical statement_1 ) then
………
block2: if (logical statement_2 ) then
………
end if blcok2
………
end if block1
block1: if (logical statement_1 ) then
………
block2: if (logical statement_2 ) then
………
end if blcok1
………
end if block2
Nest structure of if statements
Nagoya Institute of Technology
! Calculating various functions
real :: x
print *,'input a real number:'
read *,x
if(x>0.0) then
print *, sqrt(x), log(x), log10(x)
else
print *,' Not defined for x<0‘
end if
end
Intrinsic function
Example 1
Nagoya Institute of Technology
0 2 1
1
! Triangle pulse real:: x,f print *,'input x:' read *,x if(x<0.0) then f=0.0 else if (x<1.0) then f=x else if (x<2.0) then f=-x+2.0 else f=0.0 end if print *, x,f end
x<0 is already excluded
x<1 is already excluded
x<2 is already excluded
Example 2
Nagoya Institute of Technology
case nest
for many divided case <loop1:> select case ( formula ) case ( value or range of formula ) !A executable statements case (value or range of formula ) !B executable statements case default ! (otherwise) executable statements end select <loop1>
No overlap in divided case
Nagoya Institute of Technology
integer :: i print *, ‘ Enter mark ‘ read *, I if ( i<0 .or. i>100 ) stop select case (i) case (90: ) print *, ‘S’ case (80:89) print *, ‘A’ case (70:79) print *, ‘B’ case (60:69) print *, ‘C’ case default print *, ‘D’ end select end
Example
Nagoya Institute of Technology
Intrinsic function
Fundamental functions used in mathematical operatios
x, y:real、 z:complex、 i, j, k : integer
general name:return value according to type of argument x
x:single real exp(x):single real
x:double real exp(x):doube real
z:single complex exp (z) :single complex
z:double complex exp (z) :double complex
exp (x)
general name argument
sqrt(x)
abs(x)
sin(x)
exp(x)
log(x)
log10(x)
z=cmplx(x,y)
real(z)
aimag(z)
conjg(z)
aint(x) xの整数部 を実数で返す
int(x) xの整数部を整数で返す
anint(x) xを四捨五入して実数で返
す
Nint(x) xを四捨五入して整数で返
す
Nagoya Institute of Technology
Intrinsic function
aint(x) return integer part of x as real number
int(x) return integer part of x as integer number
anint(x) return real number of rounded x
Nint(x) return integer number of rounded x
Nagoya Institute of Technology
! Calculating various functions real :: x,y complex::z print *,'input a real number:' read *,x if(x>0.0) then print *, sqrt(x), log(x), log10(x) else print *,' Not defined for x<0‘ end if print *,'input a complex number x,y (=x+iy):‘ read *, x,y z=cmplx(x,y) print *, sqrt(z), exp(z), log(z) end
Example
Nagoya Institute of Technology
Note definition of complex functions of complex argument
Example for z= i
Nagoya Institute of Technology
Example for x=2 , (x,y)=(0,1)
Nagoya Institute of Technology
Exercise 4
Read positive real number and print the integer part and decimal part, separately.
Exercise 5
Enter real balues of a, b, and c for the quadratic equation ax2+bx+c=0,
and find solutions in real number according to the discriminant.
Nagoya Institute of Technology
! ex4
real:: x,y
integer:: n
read *,x
n=int(x)
y=x-aint(x)
print *,x,n,y
end
! ex5
real::a,b,c,d,x1,x2
print *,'Enter a,b,c'
read *, a,b,c
d=b*b-4.0*a*c
if(d>=0) then
x1=0.5*(-b+sqrt(d))/a
x2=0.5*(-b-sqrt(d))/a
print *, x1,x2
else
print *, 'No real solution'
endif
end
Answer
Nagoya Institute of Technology
3
Nagoya Institute of Technology
Variables need declaration of type
integer :: variable list (single precision integer 4 bytes) real :: variable list (single precision real 4 bytes) real*8 :: variable list (double precision real 8 bytes) complex :: variable list (single precision complex 8 bytes) complex*16 :: variable list (double precision complex 16 bytes)
real :: x,y
real*8 ::d1,d2
complex::z
integer :: n,m,l
Data type
Nagoya Institute of Technology
Set initial values
(once to be done when program unit is called)
Real :: pi=3.14159265,s,r
Integer :: n=30
Print * ‘Enter r’
Read *, r
S=pi*r*r
n=n+1
Print *, n,r,s
End
Real :: pi=3.14159265,s,r
Integer :: n
Print * ‘Enter r’
Read *, r
S=pi*r*r
n=30
n=n+1
Print *, n,r,s
End
Left : 30 is set for n only one time
right : 30 is always subsituted in n
give initial values in the type statement
Nagoya Institute of Technology
change types
x=real(k)
n=integer(s)
Z=cmplx(a,b)
Use intrinsic function
Implicit type declaration
Variables with the first character starting with
i,j,k,l,m,n automatically interpreted as integer
Kmin, Kmax, jnum, num
Others real
Nagoya Institute of Technology
!----- Solar year -----
real ::year,day,jikan,hun,byo
integer :: d,h,m
year=365.2422
day=aint(year)
d=int(day)
jikan=24.0*(year-day)
h=int(jikan)
hun=60.0*(jikan-aint(jikan));
m=int(hun)
byo=60.0*(hun-aint(hun))
print*,'1yearis',d,'days',h,'hours',m,'minutes', &
byo,'seconds‘
end
Nagoya Institute of Technology
Nullify of implicit type
types of all the variables need to be declared
effective to find bugs.
Change of implicit type
implicit real*8 (a-h, o-z) double precision for variables beginning with
a-h, o-z
implicit complex (z) complex for variables beginning with z
Implicit type (firts character [ range of characters]), .....
implicit none
Nagoya Institute of Technology
Logical type declaration
logical :: flag, index, range
flag=.true.
index=.false.
range =(8.0<x).and.(x<10.0)
Character type an logical type
character type declaration needs type and length(the number of characters)
character (len=8) :: c=‘doraemon’ c: character variable, `doraemon’ is content
character (2) :: fname, file, a
character ([len=]No,) :: variable list
character :: variable1*length1, variable2*length2, .....
logical :: variable list
Nagoya Institute of Technology
Program Logical_example
Implicit none
logical :: hantei
real:: a=0.e0, b=1.e0, x
read *, x
hantei=(a<x).and.(x<=b)
print *, hantei When it is true, value of decision is `T`
End false, value of decision is `F`
Example
Nagoya Institute of Technology
Named constants
parameter declaration to name constants used in program
integer, parameter :: mask=2147483467
real , parameter :: pi=3.14159265, pi2=2.e0*pi
character(1), parameter :: sp=‘ ‘, ap=“’”
character(len=*), parameter :: f=‘This is Fortran95’
* set the length to the actual length used
Type, parameter :: constant=value [or formula]
Nagoya Institute of Technology
Complex, high precision
complex :: variable list
complex*16 :: variable list
real*8 :: variable list
real([kind=]8) :: variable list
real(8) :: deg,rad,s,c
real(8),parameter :: pi=3.141592653589793
print*,'Input angle variable in degree:‘
read*, deg
rad=pi*deg/180.0
s=sin(rad)
c=cos(rad)
print*,'SIN=',s,', COS=',c
print*,'COS^2+SIN^2=',s**2+c**2
end
Nagoya Institute of Technology
!----- Complex number ----- real :: x complex :: z integer :: n complex, parameter :: i=(0.0,1.0) ! print*,'Input a real number x and an integer n:' read *,x,n; z=exp(i*x) print*,z**n print*,cos(n*x),sin(n*x) end
Nagoya Institute of Technology
Mixed operation and substitution
・for shorter variables, 0s are appended to the lower digits
・to substitute a real number for complex variable, imaginary part is set to be 0
change to the stronger type and then operate and substitute
integer < real < complex, single < double < quadruple
integer/integer returns integer
7/3 2
1/3 0
2**(-2) 1/(2**2) 0
N-m*(n/m) surplus when n is divided by m
X**n x*x*....*x
X**y exp(y*log(x))
Nagoya Institute of Technology
Substitution of different types
real :: a,b real*8 :: x a=0.0 b=2.14 x= a+b a+b addition in 4 bytes
0s are appended to lower digits to be 8 bytes
print *, a,b,x end
to compute right hand side first, to change the type of result to that of
the right hand side, and then to substitute
Real ::x
X=1.0e0/3 1.e0/3.e0 x
X=(3.14e0, 2.56e0) only real part is substituted for x
X=5 substitute 5.e0 for x
Nagoya Institute of Technology
Real::x
Real(8) ::y
y=1.0e0/3.e0 1.e0/3.e0
compute in single precision and append 0s to lower digits and substitute for y
y=2.0d0/3.e0 2.0d0/3.0d0
compute in double precision and append 0s to lower digits and substitute for y
integer ::i
i=-3.623 -3 is substituted for i
i=(3.14e0, 2.56e0) 3 for i
i=5.0e0/3 1 for i
complex ::z
z=1.0e0 z=(1.0e0, 0.0e0)
z=5.e0 z=(5.0e0, 0.0e0)
Nagoya Institute of Technology
Type of function and argument
general function name is used
y=f(x) : type of f is determined according to type of x
and change the results of f to that of y
x: double precision f: double precision
x: double precision complex f: double precision complex
Nagoya Institute of Technology
Exercise 6
1. Change 0.1e0 to double precision and compare the result with 0.1d0
2. For an integer n, print its square root computed in single and double precision.
Compute the square of the square root of a single precision real number,
and change it to that in double precision. What is difference between the original
and results?
3. Read two real numbers x and y, and make a complex number z=x+ i y.
Compute z^2 and 1/z and print them.
Nagoya Institute of Technology
4
Nagoya Institute of Technology
Iteration
powerful ability of computers (no tired)
do loop
[label:] do do-variable=initial, limit [, increment]
・・・・
end do [label]
integer :: n,sum=0
do n =1,100
sum=sum+n*n
end do
print *,sum
end
defalt 1
negative value is also allowed
do n =1,100,2
do n=2,100,2
do n=100,1, -1
do n=1,2, -1 When the initial value exceeds the limit value in the driection of increment, no execution
After exiting the loop, n=101
Nagoya Institute of Technology
loop1: do j=1,n
………
loop2: do i=1,m
………
end do loop2
………
end do loop1
Multiple do loop and nesting
loop1: do j=1,n
………
loop2: do i=1,m
………
end do loop1
………
end do loop2
Nagoya Institute of Technology
Exiting loop
do i=1,m
………
if( a> eps) exit
………
end do
………
exit
cycle
do i=1,m
………
if( a> eps) cycle
………
end do
Jump to the line after the end do line
Jump to the End do line
Nagoya Institute of Technology
integer :: m,n,mn
var1:do m =2,9
var2: do n =1,9
print *,m,'*',n,'?'
read *,mn
if(mn==m*n)then
print *,‘Correct'
else
print *,‘wrong'
end if
end do var2
end do var1
end
Nagoya Institute of Technology
Format for input and output
For easiness of reading large amount data
Print format, output list
Write(*, format) output list
* : standard (input : key board, output : display)
‘(list of format item)’ (list of format item) is interpreted as character constant
character :: fmt*21
..........
fmt=‘(_1x,_i3,_2x,_3F10.5)’ 21 characters including (, space , )
print fmt, k,s,c,p
.........
number format (list of format item) any place within a program unit is allowed
print 100, k,s,c,p
100 format ( 1x, i3, 2x, 3F10.5)
Format
Nagoya Institute of Technology
Format field descriptor integer : w, d, n, r
Iw for integer data, w : width (in character unit), stuck from the right I5 : 56789
Fw.d for real data, w : width, stuck from the right,
d : digits after decimal poin w≥ d+2
F5.2 : □2.35 , -4.12
Ew.d for real data in the floating form with exponent of 10 w≥ d+7
Dw.d for real double precision data in the floating form with exponent of 10 w≥ d+7
Aw for character data w : width, stuck from the right A5 : abcde
A adjust to the actual number of characters
r ….. Iterate by r times (….)
nX skip by n spaces. can not omiteven when n=1 1x : □ 3x : □ □ □
‘……’ write directly string in the format ‘This is an example.’
“……” the same as the above ‘(1x, I3,1x, “Hx=“, F5.3)’
d
w E12.5: -0.23452E-01
5
12
Nagoya Institute of Technology
continued
/ change line
( ) repeat ‘(/, 3(1x, e12.5))’
print *
write(*,*) write a blank line
read * for characters ‘AKB48’
read ‘(A)’ just type as you want Hello
Nagoya Institute of Technology
!ex5-3 !----- Table of SIN and COS ----- real, parameter :: rad=3.1415926/180.0 real :: r,s,c,p integer ::k print *,"kakudo SIN COS CHECK“ do k=0,90,10 r=k*rad s=sin(r) c=cos(r) p=s*s+c*c print '(1x,i3,2x,3f10.5)',k,s,c,p end do end
Nagoya Institute of Technology
!ex5-4 !----- Mean and Standard Deviation ---- integer :: n=0,mark real :: w=0.0,v=0.0,mean,sd do print *,'score ( 0<x end)' read *,mark if (mark<0)exit n=n+1 w=w+mark v=v+mark**2 end do if(n>0)then mean =w/n; sd=sqrt(v/n-mean**2) print '("average=",f5.1)',mean print '("sd=",f5.1)',sd end if print '("total=",i5)',n end
mean
standard deviation
Nagoya Institute of Technology
Avoid Infinite loop
!ex5-5 !---- the greatest common divisor --- integer :: m,n,k print *,'Imput two integer m,n(>0):' read *,m,n if(m>0 .and. n>0)then do k=mod(m,n) if (k==0) exit m=n n=k end do if (n/=1)then print *,‘the greatest common divisor =',n else print *,'nothing' end if end if end
Guarantee to exit from do loop
Nagoya Institute of Technology
3からの奇数をqまで虱潰しに調べる. このqは以下のようにして求め
ることができる.いま, qまで調べたとすると、このqの整数倍は素数
ではない. すなわち q*1,q*2,q*3,…, q*m は除外される.こうし
て調べられるmの最大はqまで.mがq以上ならmとqを取り換えればよい.
このq*qがn以上であればすべて網羅したことになるので、 q*q ≥ nと
見積もれる.
n
1
2
3
1 2 3 m
q 3 n
! --- Prime Number upto 100 --- Integer :: n, m, q, max=1000 print *, 2 ! no search for even numbers except 2
loop: do n = 3, max, 2 q=Nint(sqrt(real(n))) do m = 3, q, 2 ! Examine all the odd numbers up to q
if( mod(n,m)==0 ) cycle loop ! When it is divided, it is not prime number
! and exit the loop
end do print *, n ! When the loop is passed, it is a prime number
end do loop ! Jump to here by cycle statement
end
Suppose the prime numbers up to q are found.
Since mulitples of q like q*1, 2*2, q*3 are not prime numbers,
Those numbers are excluded from the search for numbers >q.
The maximum number m examined in this way is q.
When n is greater than q, switch m and q.
When q*q >=n, all the possible numbers are examined
and thus search is finished
Nagoya Institute of Technology
do while
[label] : do while ( logical formula)
…………
end do [label]
do i=1,100
………
end do
i=1 do while (i<=100) ……… i=i+1 end do
i=1 do while (i<=100) i=i+1 ……… end do
The case i=101 is executed Caution! the position of i=i+1
equivalent
Nagoya Institute of Technology
!ex 5.7 ! Computation of sqrt(x) by recursive equation implicit none Real:: r=0.e0, x, d=1.e-5 Do print *,'Input a positive real number' read *, r if(r>0.e0) exit End do x=r do while (abs(x**2-r)/r >d) x=0.5e0*(x+r/x) end do print '(1x,e12.5)’, x end
Convergence criterion:
Nagoya Institute of Technology
Exercise 7
The Fibonacci sequence is given by
Find x_n for n=1, ...,50 and print n and x_n in one line
Compute the ratio x_n/x_{n-1} and observe whether the ratio converges as n increases.
Nagoya Institute of Technology
Simple formula
Trapezoidal rule
Simpson’s rule
Numerical integration
x0 x1 xj xn
h
f j
f(x)
x
Nagoya Institute of Technology
1. Calculate analytically (leave algebra on note)
2. Numerically integrate by two methods and compare the results with
the anaytical results obtained in 1.
3. Observe the convergence by changing the number of grid points
Simple rule and torapozidal rule
Torapezoidal rule and Simpson‘s rule
Torapezoidal rule and Simpson‘s rule
when the upper limit is infinite, choose a finite value L and increase it gradually
and see the convergence. It is also useful to plot the function and to see how fast
the function decays.
Exercise 8
Nagoya Institute of Technology
5
Nagoya Institute of Technology
Array
Vector, Matrix
Declaration of array (1 dim.)
type, dimension([bottom: ] top) :: list of array names
type:: array1([bottom: ] top) , array2([bottom: ]top) , ….
Integer, dimension (1:100) :: number,mask
Real :: x, r, a(-100:100)
Complex, dimension(-100:0) :: zk, wk
Character, (len=1) :: fname(1:20)
default 1
x and r are scalars
size=top – bottom + 1
number 101
a 201
zk 101
fname 20
array element : specify by the number
33rd element of number : number(33)
-4th element of zk : zk(-4)
Nagoya Institute of Technology
Initial setting of array
Constant array (/const, const, …/)
Do type iteration ( / (data list, do variable=initial, limit[, increment] ) / )
Integer :: a(0:9)=(/0,1,2,3,4,5,6,7,8,9/)
Integer :: n, a(0:9)=(/(n,n=0,9)/), b(1:10)=(/(2**k,k=1,10)/)
Real, dimension(0:2) :: x=(/1.0e0, 2.0e0,. 3.0e0/)
Integer ::n
real ::w(0:2)=(/(0.5e0**n, n=0,2)/)
Real::x, s(0:7)
x=2.0e0
S=(/(x,n=1,8)/)
Array structure specification (/data list/)
(/(x,n=1,8)/) can be used in the
execution statement
Nagoya Institute of Technology
Operations for array
Simultaneous operations: substitution, addition, subtraction, multiplication
(1) Partial array
Array name ([initial index] : [limit] [:increment )
Integer :: a(1:5)=(/2,4,6,8,10/)
a(4:) a(4:5) (/8,10/)
a( :3) a(1:3) (/2,4,6/)
a( : ) a(1:5) (/2,4,6,8,10/)
a(1:5:2) (/2,6,10/)
a(5:1:-1) (/10,8,6,4,2/)
a(3:3) (/6/) a(3:3) 1 dim. array with 1 element
Real :: x, a(5)=(/(2**n, n=1,5)/)
a(3:3)=x OK
x=a(3:3) NO x: scalar, a: 1dim. Array
Nagoya Institute of Technology
(2) Array substitution
Array=other array with the same shape ( Shape: size and dimensionarity)
Integer :: n, a(1:10), b(1:5), c(1:16)
a=(/(n,n=0,9)/)
b=a(1:5)
c(1:10)=a
c(12:16)=a(6:10)
c(11)=1
c(11:11)=1
b=0 all elements are 0
c(1:10:2)=1 odd numbers elements are1
c(2:10:2)=0 even number elements are 0
Nagoya Institute of Technology
i
1
2
1 2
j
i+1 n
i
n
Find maximum
swap
!----- Sorting Array Elements -----integer::m,mark(100),n=0,max,maxi,i,j do while(n<=99) print*,"Input integer,or negative one to stop:" read*,m; if(m<=0) exit n=n+1; mark(n)=m end do !----- Sorting do i=1,n-1 max=mark(i) maxi=i do j=i+1,n if(mark(j)>max) then max=mark(j) maxi=j end if end do if(maxi/=i) then mark(maxi)=mark(i) mark(i)=max end if end do !----- Output do i=1,n print"(' Rank',i3,' =',i10)",i,mark(i) end do end
Sorting
Nagoya Institute of Technology
(3) Array arithmetic operations
Short expression of the operations for elements in terms of array names alone
Integer, dimension(1:50) :: sum, dif, pro, div &
even=(/(2*i, i=0,49)/), odd=(/(2*i+1, i=0,49)/)
Real, dimension(1:20) :: a, b=(/(2.0e0**n,n=0,19)/)
sum=even+odd sum( : )=even( : )+odd( : )
dif=even-odd dif( : )=even( : )+odd( : )
pro=even*odd pro( : )=even( : )*odd( : )
div=even/odd div( : )=even( : )/odd( : )
a=sqrt(b) a( : )=sqrt( b( : ) )
real::x(0:4)=(/(2.0**n,n=0,4)/)
x=x(0:4)*x(4:0:-1)
print*,x
end
Nagoya Institute of Technology
(4) Vecrtor operation
Simultaneous operations for the arrays
Integer :: a(0:9)=(/0,1,2,3,4,5,6,7,8,9/)
Reults of A differ from those of B !
a(1:9)=a(0:8)
do i=1,9
a(i)=a(i-1)
end do
a(0) a(1) a(2) a(3) a(4) a(5) a(6) a(7) a(8) a(9)
a(0) a(1) a(2) a(3) a(4) a(5) a(6) a(7) a(8) a(9)
0 0 1 2 3 4 5 6 7 8
a(0) a(1) a(2) a(3) a(4) a(5) a(6) a(7) a(8) a(9)
time
time
0 0 0 0 0 0 0 0 0 0
A
B
Nagoya Institute of Technology
(5) Array inputs and outputs
to use array name or to use do statetment
Integer :: a(10)=(/(n,n=1,10)/)
print '(10I5)', (a(i), i=1,10)
print '(10I5)', a
print '( 5I5)', a(1:5)
print '(10I5)', (a(i), i=10,1,-1)
print *
do i=1,10
print '(10I5)', a(i)
end do
end
10 elements in one line
10 lines each of which contains one element
Nagoya Institute of Technology
!----- Pascal's Triangle -----
integer, parameter::max=12
integer::i, c(0:max)=0
c(1)=1
do i=1,max
c(1:i)=c(1:i)+c(0:i-1)
print'(i2,":",50i5)',i,c(1:i)
end do
end program
1
1 1
0 1 2 1 0
1 3 3 1
1 4 6 4 1
i
max
Nagoya Institute of Technology
Multi dimensional array
type, dimension ([bottom1:] top1, [bottom2:] top2, ....) :: array list
type:: array1 ([bottom1:] top1, [bottom2:] top2, ....) , ….
real :: a(1:3,1:3), x(1:3), y(1:3), z(1:3)
x=a(1,1:3) or x=a(1,:)
y=a(2,1:3) or y=a(2,:)
z=a(3,1:3) or z=a(3,:)
Order of elements and structure on the memory of multidimensional array
real :: a(1:3,1:2)
メモリー上に記録される仕方
a(1,1) a(1,2)
a(2,1) a(2,2)
a(3,1) a(3,2)
do i=1,10000
do j=1,10000
a(i,j)=i+j
end do
end do
do j=1,10000
do i=1,10000
a(i,j)=i+j
end do
end do
The same results but the left is faster than the right
Nagoya Institute of Technology
Dynamic allocation of arrays
type, allocatable :: array1(:, :, ….) list
type, dimension (:, :, …) , allocatable :: array list
……
allocate (array1(range of size), …. )
……
deallocate(array1, …. )
integer :: upper_limit
integer, allocatable :: freq(:)
.....
read*, upper_limit
allocate(freq(1:upper_limit))
.....
deallocate(freq)
Allocate the required arrays in execution and deallocate after completed
real, dimension(:,:), allocatable :: x,y
.....
n=1000
allocate(x(n,n),y(2*n,2*n))
.....
deallocate(x,y)
Nagoya Institute of Technology
!----- Matrix Product ----- integer,dimension(:,:),allocatable::a,b,c integer::m=0,n=0,k=0,i,j,h ! do while(m<=0.or.n<=0.or.k<=0) print*,"Input Array Size m, n, k ( > 0) :" read*,m,n,k end do allocate(a(m,n),b(n,k),c(m,k)) ! print*,"Input Elements of A in a Matrix Form:" read*,((a(i,j),j=1,n),i=1,m) print*,"Input Elements of B in a Matrix Form:" read*,((b(i,j),j=1,k),i=1,n) ! do i=1,m do j=1,k c(i,j)=0 do h=1,n c(i,j)=c(i,j)+a(i,h)*b(h,j) end do end do end do do i=1,m print"(10i5)",(c(i,j),j=1,k) end do end
Nagoya Institute of Technology
where
where (selection rule)array substitution
Integer a(50),a1(50)
where ( a>=40) a1=nint(2.0e0*(a+50)/3.0e0) simultaneous substitution
Execute the substitution to the array only for the elements at which a condition is satisfied
where
[label:] where (selection rule 1)
array substitutions
elsewhere (selection rule 2)
array substututions
end where [label]
Nagoya Institute of Technology
forall
forall (range of index,[selection rule])array substitution in index
index=[initial] :[limit] [:increment]
forall (i=1:1000, mark(i)>=60) mem(i)=‘pass’
forall (i=1:100, j=1:100) a(i,j)=i*j
forall (i=0:90) s(i)=sin(0.0174533e0*i)
forall (i=0:7, j=1:7, a(i)<0) b(i,j)=0
forall (i=1:9) a(i)=a(i-1) simultaneous substitution
Nagoya Institute of Technology
forall(i=1 : mem, mark(i)>=60)
mark(i)=nint(2.0e0*(mark(i)-40)/3.0e0+60
list(i)=‘pass’
End forall
forall
[label:] forall (formula for index,[selection rule])
substitution operations with index
end forall [label]
Nagoya Institute of Technology
integer::m=0,n=0
real,allocatable::a(:,:)
do while(m<=0.or.n<=0)
print*,"Input Array Size m, n ( > 0) :"
read*,m,n
end do
allocate(a(1:m,1:n))
print*,"Input Elements of A:"
read*,(a(i,1:n),i=1,m)
where(a<0) a=0.0
do i=1,m
print"(10f8.5)",sqrt( a(i,1:n) )
end do
end
Nagoya Institute of Technology
6
Nagoya Institute of Technology
Character data
Interface between man and machine
Declaration of character
character (len=8) :: a,b,c=‘doraemon’
character :: fname(1:10)*8
character ([len=] length) :: variable name list
character :: name1*length, name2*length2,・・・・
character :: array([bottom:] top) *length,・・・・
Partial string of character
Part of character string
Variable name of character([bttom] : [top])
character (len=8) :: c=‘doraemon’ C(3:3) r r C(4:8) emon
Nagoya Institute of Technology
Substitution
Length of the left hand side= Length of the right hand side
character (len=8) :: c
<
D o r a e m o n
> D i r a c
Pading from the left side
Extra part is cut off
character (len=8) :: a=‘abcdefgh’ a(1:5)=a(2:6) ‘bcdeffgh’
a(2:6)=a(1:5) ‘aabcdegh’
K o l m o g o r o v
Nagoya Institute of Technology
!---- Hexadecimal Representation ---- Implicit none Integer :: dec, i character(len=1) :: h(0:15)=(/'0','1','2','3','4','5','6','7' & ,'8','9','A','B','C','D','E','F'/) character(len=8) :: hex ext: do hex=" " print*, "input a positive integer,or 0 to stop:" read*, dec; if(dec<=0) exit ext hxd: do i=0,7 hex(8-i:8-i)=h(mod(dec,16)) dec=dec/16 if(dec==0) exit hxd end do hxd print ‘(1x,A8)’, hex end do ext end
Fill from the left
Go to the next digit
Hexadecimal expression
4 0 E
232=168=(24)8
Nagoya Institute of Technology
Character (1) :: f(9)=(/'1','2','3','4','5','6','7','8','9'/) Character (22):: fmt Integer :: n,k n=2; k=3 Read *, int fmt="( 2x, 'Int = ', "//f(n)//"I"//f(k)//" )" Print fmt, int end
Concatination of character strings
string1 // string2
character:: a*9,f*7='Fortran', g*2='95' a=f//g Print '(1x,a9)', a f='boy' g='s' a=f//g print'(1x,a9)', a end
Fortran95
boy____s_
Print ( 2x, ‘Int = ’, nIk ), int
Nagoya Institute of Technology
!---- rearrange characters of a word---- character(len=5) :: w0,w1,w2,w(1:24) integer :: i,j,k,n=1 print*,“input a word in 4 letters: " read '(a)',w0 do i=1,4 w1=w0(i:i)//w0(1:i-1)//w0(i+1:5) do j=2,4 w2=w1(1:1)//w1(j:j)//w1(2:j-1)//w1(j+1:5) do k=3,4 w(n)=w2(1:2)//w2(k:k)//w2(3:k-1)//w2(k+1:5) n=n+1 end do end do end do print '(/12a5))', w end
Sorting of characters
b l u e
u l b e
1番目に来る文字を先頭から順に選ぶ
2番目に来る文字を2番目以降から順に選ぶ
Nagoya Institute of Technology
Input and output of data
On the cosole (Key board and display)
print format, output list
read format, output list
1. To store and extraction of small size of data
f=‘( A10, F10.5 )’ write(6,f) x write(*,‘( A10, F10.5 )’ ) x print‘( A10, F10.5 )’, x
f=‘( 3I10 )’ read(5,f) i,j,k read(*,‘( 3i10 )’) i,j,k read(*,100) i,j,k 100 format(3i10)
same
Nagoya Institute of Technology
Input and output of data
Assignment of file name of the input and output data
open, close
open([unit=]file equip.no , file=filename [,control item])
close([unit=]file equip.no, file=filename [,control item])
CPU DISK
open(10,file=‘ data1’)
open(20,file=‘ data2’)
read(10) u1
write(20) u2
close(10)
close(20)
data1 u1
data2 u2
open(10,file=‘ data1’)
open(20,file=‘ data2’)
Input and output of data on the specified file
write([unit=] file equip.no ,[fmt=]format [, control item ])output list
read([unit=] file equip.no ,[fmt=]format [, control item ])output list
2. A large amount of data on hard disk
To connect or disconnect to hard disk
Nagoya Institute of Technology
Identification of equipment
• Write the equip.no. first when ``unit” is not used
• File no. should be positive integer variable (include mathematical expression) or constant
• File name should be character variable or character constant
Control item
iostat= integer variable i normal i = 0
error i > 0
status=‘ string ‘ old : file exist
new : no other file with the same name
replace : overwrite on the same name file
unknown : new for input , replace for output
delete : delete after use (only for close statement)
if ``status=“ is skipped, d efault is unknown
position=‘string ‘ rewind : start from the beginning
append : add at the end of file
open, close
open([unit=]file equip.no , file=filename [,control item])
close([unit=]file equip.no, file=filename [,control item])
Nagoya Institute of Technology
Identification of equipment
* console (key board)
Number file equipment no. specified by open statement
6 console (display)
Character variable inner file
Control item
iostat= integer variable i normal i = 0
error i > 0
end of file I < 0
advance=‘no’ no change of line after input or output
Input and output with file specification
write([unit=] file equip.no ,[fmt=]format [, control item ])output list
read([unit=] file equip.no ,[fmt=]format [, control item ])output list
Nagoya Institute of Technology
character::d*10 Integer ::p=123456789 write(d,’(i10)’ ),p d=‘_123456789’ substituted character string at d
from the right
Inner file
Input and output without format
Very fast and efficient for input and output for binary data (large volume of data)
real*8, dimension(-10000:10000) :: a,b,c,d read(10) a,b write(20) c,d
Nagoya Institute of Technology
Open (8,file=‘result’) Write(8,’(8f10.7)’) (x(i),i=1,8) close(8)
character(80) :: line(1:1000) open(11,file=‘../mydata/report.txt’) do j=1,1000 read(11,’(a)’,iostat=io) line(j) if(io<0) exit end do close(11)
character:: filename*10 print*, ‘Input file name?’ read ‘(a)’, filename open(10,file=filename)
Example 1
Leave do loop when the end is found
Nagoya Institute of Technology
read(8,’(i10)’,iostat=i) k If(i>0) stop ‘Input file error’
character(4) :: fn . . . . irun=32 write(fn,'(i4.4)') irun open(10,file=‘int_'//fn//‘.dat') open(20,file=‘spect.dat’) . . . . write(10,’(1x, 2(f7.4,1x))’) time,esum . . . . write(20) (energy(i), i=1,kmax) close(10) close(20)
Example 2
Example 3
Inner file
Create new file ``Int_0032.dat”
Create new file ``spect.dat”
Write data at `` Int_0032.dat”
Write data at `` spect.dat”
iw.m : write w digit integer from the right when the number is shorter than m digit, 0 s are appended to the left. irun=32 0032
Nagoya Institute of Technology
Miscellaneous
backspace([unit=]file unit no., isostat=integer variable)
rewind([unit=] file unit no., isostat= integer variable )
Back to the previous record point
Back to the head of the file
endfile([unit=] file unit no., isostat= integer variable )
Write the end of file
Nagoya Institute of Technology
!------ Character Code Table ------ integer ::i,j open(8,file='Code_table') do i=0,31 write(8,"(7(2x,i3,2x,a))")(i+32*j,char(i+32*j),j=1,7) end do close(8) end
Nagoya Institute of Technology
7
Nagoya Institute of Technology
Sub program
indispensable to make sturctured program
…..
call sub_A
call sub_B
…..
call sub_C
….
call sub_A
….
end
sub_B
sub_A
sub_C
call sub_G
Mail program Sub program Subroutine To do specified routine work only
can be used in other program
sub_G
Nagoya Institute of Technology
subroutine example
Read three numbers and sort them in the ascending order
Main program
Sub routine
Dummy arguments
Actual arguments
implicit none integer :: i,j,k read *,i,j,k if(i<j) call swap(i,j) if(j<k) call swap(j,k) if(i<j) call swap(i,j) print *,i,j,k end ! ! ! subroutine swap(p,q) integer :: p,q,r r=p; p=q; q=r end
Nagoya Institute of Technology
subroutine name [(list of dummy arguments)]
……….. end subroutine [name]
Subroutine
call subroutine_name[ (list of dummy arguments) ]
call
return
return
Set the return point to the main program
……… call sub(…,code) select case(code) case(1) …… case(2) …… default …… end select ……
subroutine sub(…,return_code) …… return_code=1 return …… return_code=2 return …… return_code=999 end subroutine sub
Variables, Arrays
Nagoya Institute of Technology
Subprogram
・ Only one main program
・ No limits on the number of subprograms
・ Allowed to call other subprograms from one subprogram
・ Not allowed to call itself from subprogram
(except reccurence statement)
・ The number, types, size, shape of the actual and dummy arguments
must be identical
Nagoya Institute of Technology
integer, parameter::n=100 real, dimension (0:n):: x,y ……… call set_initial(x,y,n) ……… End ! subroutine set_initial(a,b,m) integer :: m,i real, dimension(0:m)::a,b do i=0,m a(i)=0.0 b(i)=0.0 end do end set_initial
Number, type, shape of dummy arguments
Number, type, shape of actual arguments
call set_initial(y,x,n)
subroutine set_initial(a,b,m)
The number, types, size, shape of the actual and dummy arguments must be identical
Order of variables important
The data are passed according to the order
・Coinsident ot the numebr, types, shapes of arguments
・Order
・Correspondence between the variables in actual and dummy arguments
no need of the same name
Nagoya Institute of Technology
Effective range of variables
Variable name, sentence no. and structure name are effective in one
program only
…..
call sub_A
….
y=sin(2.0*x)
….
print *, x,y
end
Subroutine sub_A
….
x=2.0*k
y=exp(-x)
…..
end subroutine sub_A
Main program Subprogram
No share of x,y
How share?
Nagoya Institute of Technology
Method of sharing
1 aruguments
2 use common
3 use module
1.Arguements
call set_initial(x,y,z,n) subroutine set_initial(a,b,c,m)
2. common
common[/common block/]list
common/param1/x,y,z Common/param2/a,pi ….
common/param2/s,pi ….
Program 1 Program 3
common/param1/p,q,r ….
Program 2
(x,y,z) (p,q,r) (a,pi) (s,pi)
・number, types, shapes
・order
・no need to use the same name
(x,y,z,n) (a,b,c,m)
・number, types, shapes
・order
・no need to use the same name
Nagoya Institute of Technology
save
No guarantee to preserve the value of variable defined
in subprogram for the next call
Use save statement
integer :: n real :: z do n=1,100 call sub_A(z,n) …… end do end
Main Program Sub program
subroutine sub_A(w,k) real, save :: pi …… if(k==1) then …… pi=3.14159265 end if w=cos(0.1*pi*k) …… end subroutine sub_A
Not sure if the value of pi is preserved unless save is made
Nagoya Institute of Technology
Attribute of input or output of dummy arguments
Specify input (in) or output (ou) of arguments
type, intent(in, out, inout)::list
intent
implicit none integer :: i,j,k read *,i,j,k if(i<j) call swap(i,j) if(j<k) call swap(j,k) if(i<j) call swap(i,j) print *,i,j,k end
subroutine swap(p,q) implicit none integer, intent(inout) ::p,q integer :: r r=p; p=q; q=r end
Nagoya Institute of Technology
Example1
!------Drawing a Histogram -------- integer :: nn(0:9),j character(len=80) :: cn character(len=30) :: fmt nn=(/1,5,12,22,28,35,48,28,10,3/) fmt='(1x,i2,"-",i2,1x,a50)' do j=0,9 call str(nn(j),cn) print fmt,10*j,10*j+9,cn end do end ! subroutine str(n,c) integer, intent(in) :: n character(len=80), intent(out) :: c integer ::k c=‘ ‘ c(1:1)='I' do k=2,n+1 c(k:k)='#' end do end
Try to use comment ! c=‘ ‘
I#########
50-59 I############ write
Nagoya Institute of Technology
Example 2
subroutine count(n) implicit none integer, intent(out) :: n integer :: i, sum=0 ! sum=0 do i=1,10 sum=sum+i end do n=sum end subroutine count ! Program main implicit none integer :: n call count(n) print '(1x,i6)',n call count(n) print '(1x,i6)',n end
Set initial value of sum
n=55
n=110
sum=55 in the previous step remains
Set sum=0 at each time
Nagoya Institute of Technology
External function
Function defined by programer
External function: subroutine, external function
Built-in function : Mathematical function already built-in the fortran
[type] function name(argument list)[result(variable names)]
………
end function name
Function subprogram
function name( argument list )[result( variable names )]
type :: function name or result variable name
………
end function name
Function name (or result variable name)= formula
Substitution of function value
Nagoya Institute of Technology
Function name (or result valuable name)= formula
Substitution of function value
integer :: n=100 real :: x,dx,sum=0.0,a=1.0 dx=1.0/n do i=1,n-1 x=i*dx sum=sum+fr(x,a) end do sum=(sum+0.5*(fr(0.0,a)+fr(1.0,a)))*dx print ‘(1x,e10.3)’,sum end ! real function fr(x,p) real :: x,z,p z=(p-x*x)/(p+x*x) fr=log(z) end function fr
Referring the external function
Function name (actual argument list)
Trapezoidal rule
・Coinsident ot the numebr, types, shapes of arguments
・Order
・Correspondence between the variables in actual and dummy arguments
no need of the same name
Nagoya Institute of Technology
!-- Generating a Hexadecimal Representation ------- function hex(n) character(len=8) :: hex character(len=1) :: h(0:15)=(/ '0','1','2','3','4','5','6','7',& '8','9','A','B','C','D','E','F'/) integer, intent(in) ::n integer :: nin,j,nn hex=' ' nin=n do j=8,1,-1 nn=nin/16 hex(j:j)=h(nin-16*nn) if(nn==0) exit nin=nn end do end function hex !---- Main ---- program main implicit none character(len=8) :: hex integer :: i print *, 'Input a positive Integer or negative one to stop:' do read *, i; if(i<0) exit print *,hex(i) end do end
From the right
Example
Input n
Hexadecimal expression
Nagoya Institute of Technology
type, external :: function list
external :: function list
Declaration of function attributes
Let the compiler know that the function is external
external
type, intrinsic :: function list
intrinsic :: function list
intrinsic The external function is chose n when the function name is the
same as the built-in function
call integral(gamma,0.0,1.0,s) ………… real function gamma(x) …………
Declaration of attribute is neccessary for function argument
Nagoya Institute of Technology
implicit none real:: h, phix,err real, external ::Gaussian print *, 'What is your deviation value?' read *, h h=(h-50.0e0)/10.e0 call simpson(Gaussian, 0.0e0,h, 16,phix) err=(0.5e0-phix)*100.0e0 print '(1x,a,f6.2,a)', & 'From the top you are ', err, ' %.' end subroutine simpson(func,a,b,kubun,integ) implicit none integer, intent(in)::kubun integer:: i real, external :: func real, intent(in) :: a,b real, intent(out) :: integ real :: x,dx dx=(b-a)/(2.0e0*kubun) integ=func(a)+4.0e0**func(a+dx)+func(b) do i=1,kubun-1 x=a+(2.0e0*i)*dx integ=integ+2.0e0*func(x)+4.0e0*func(x+dx) end do integ=integ*dx/3.0e0 end subroutine simpson
real function Gaussian(s) implicit none real, parameter :: rn=2.506628e0 ! \sqrt(2*pi) real, intent (in) :: s Gaussian=exp(-s*s/2.0e0)/rn end function Gaussian
Simpson‘s formula
x
Example
Nagoya Institute of Technology
Contains
To include subroutines and functions in one program unit
integer :: n real :: z,g,pi pi=3.14159265 do n=1,100 call sub_A(z,n) …… g=func(z) …… end do ……… Contains subroutine sub_A(x,m) ……… z=log(func(x)) ……… end subroutine sub_A ! real function func(x) ……… func=0.5*exp(-pi***0.25d0) end function func end
The same rules for subroutine and function apply
contains
1.No declaration of type and attributes of internal function
2.Variables and arrays defined in the parent program are
effective in the child program and the same values are shared
3.When the same variable names as in the parent program are declared,
they are effective only in the child program and not shared.
4.Conatins statement is not allowed in the internal procedure
5.Referring other internal procedure from one internal procedure
is allowed when the two are in the same parent program
6. There must be ``subroutine, function“ in the end statement in
the contains program
Nagoya Institute of Technology
Example
!----- All Round Calendar ------ program main character(len=9) :: name(0:6)=(/'Sunday ', & 'Monday ', 'Tuesday ','Wednesday', & 'Thursday ','Friday ','Saturday '/) integer :: md(1:12)=(/31,28,31,30,31,30,31,31,& 30,31,30,31/) integer :: y,m,d,ld do print *,'year?' read *,y; if(y<=0) exit md(2)=28+leap(y) print *,'month?‘ do read *,m; if(0<m .and. m<=12) exit print *, 'm<=12' end do print *, 'Day?' read *, d if(d<=0 .or. d>md(m)) then print *, 'nothing' else call count(ld) print "(1x,i5,',',i2,',',i2,',',a9,a/)", & y,m,d,name(ld) end if end do
! contains ! Count how many days since Jan. 1, 0001 ! and compute what day is subroutine count(n) integer, intent(out) :: n n=yday(y)+sum(md(1:m-1))+d n=mod(n,7) end subroutine ! ! Count how many dasys on Dec. 31 of ! the last year since Jan 1, 0001 function yday(x) result(days) integer :: x,days days=365*(x-1)+(x-1)/4-(x-1)/100+(x-1)/400 end function yday ! integer function leap(x) ! 1 for leap year ! 0 otherwise integer :: x leap=yday(x+1)-yday(x)-365 end function leap ! end program
Nagoya Institute of Technology
Sharing of arrays
quite often used in numerical computation
pass the arrays in the main program to subprograms accoring to
their shape and size
1.explicit shape array
2.assumed shape array
array of explicit shape with fixed upper and bottom boundary (static)
array that has no size specification except shape in the declaration
statement of subprogram and its size is fixed by the size of the actual
arguments when it is referred. (dynamic)
Nagoya Institute of Technology
Explicit shape array
Array of explicit shape with fixed upper and bottom boundary (static)
Subroutine sub(x,n)
integer, intent(in):: n
integer :: a(1:n),j
real, intent(out) :: x
real, allocatable ::temp(:)
allocate(temp(0:n))
1.Dummy integer variables which are passed from the parent program
2.Value obtained by the size function applied to dummy array
3.Integer variable shared by common statement
4.Integer variables of the internal procedure that are shared with those of
the parente program
Method of passing size
a(1:n) and temp(:)
are not the dummy arrays but
used only in the subroutine
Nagoya Institute of Technology
program main integer, allocatable :: number(:) integer ::n,m,i print *,‘How many applicants?’ read*,n No. Of applicants print *, ‘How many winners?’ read*,m No. Of winners allocate(number(n)) call chusen(number,n,m) ! print *,‘順位 当選番号’ do i=1,min(n,m) print '(2x,i4,i8)',i,number(i) end do end subroutine chusen(kk,n1,n2) integer, intent(in) :: n1,n2 integer, intent(out) :: kk(n1) integer :: i,ir,j,temp real ::x kk=(/(i,i=1,n1)/) print *,'ir' read *, ir do i=1,min(n1,n2)-1 call ran(ir,x) j=i+int(x*(n1-i+1)) temp=kk(i) kk(i)=kk(j) kk(j)=temp end do end subroutine
Example
subroutine ran(i,r) integer, intent(inout):: i real, intent(out) :: r integer, parameter ::mask=2147483647,a=48828125 i=iand(a*i,mask) r=real(i)/real(mask) end subroutine
Generate pseudo
random number (0,1)
Seed of random number (enter any positive integer
Choose n winners out of m applicants
Random number (0,1)
Choose one out of the residuals
Swap I and j
Nagoya Institute of Technology
Assumed shape array
array that has no size specification except shape in the declaration
statement of subprogram and its size is fixed by the size of the actual
arguments when it is referred. (dynamic)
integer, parameter:: n=100 real :: u(0:n,0:n),x(0:n),y(0:n) interface subroutine fmake(w,a,b) real, intent(in)::w(0:,0:),a(0:) real, intent(out)::b(0:) end subroutine fmake end interface ………… call fmake(u,x,y) ………… end
Parent program Sub program
subroutine fmake(w,a,b) real, intent(in)::w(0:,0:),a(0:) real, intent(out)::b(0:) integer ::m Real :: sum m=ubound(w,1) do i=0,m sum=0.0 do j=0,m sum=sum+w(i,j)*a(j) end do b(i)=sum end do end subroutine fmake
Upper limit in the first
dimension of w
Array size is determined by the
size of the actual argumenst
Interface statement
Let the compiler know the program structure in advance
Nagoya Institute of Technology
Subroutine test(x) implicit none real :: x(:) ! real :: x(0:) print ‘(2i3)’, lbound(x), ubound(x) end subroutine test Program main implicit none integer :: I real :: s(-10:10)=(/(i,i=1,21)/) interface subroutine test(x) real :: x(:) end subroutine test end interface call test(s) call test(s(0:8)) End
Return 1 and 21 Return 1 and 9
Example 1
Interface
procedure name to be referred
shape, attributes of dummy arguments
end interface
interface structure
Nagoya Institute of Technology
program main integer :: n,i real, allocatable :: a(:,:) interface function trace(x) result(tr) real, intent(in) :: x(1:,1:) real :: tr end function end interface print *,'n?' read *,n allocate(a(1:n,1:n)) do i=1,n ! print '(1x,a,i2)','line',i do j=1,n print '(1x,a,i2,a,i2,a)', & 'Enter element a(',i,' ,',j,')' read *,a(i,j) end do end do print '(1x,a,F7.4)','trace=',trace(a) end
Example Trace of square matrix
!----Trace of a Square Matrix function trace(x) result(tr) Implicit none integer :: n1,n2,i real, intent(in) :: x(1:,1:) real :: tr n1=size(x,1) ! See Text p.82 n2=size(x,2) if(n1/=n2) then print *, 'not square';return else tr=0.0 do i=1,n1 tr=tr+x(i,i) end do end if end function
Nagoya Institute of Technology
Arrays in contains
Allowed to use the same integer variable names as those defined in parent program
implicit none real, dimension(1:3) :: a,b,c,bc print *, "Input three vector's components" read *, a read *, b read *, c bc = vector_prod(b,c) print '( "Sp3 = ",F10.3)', scalar_prod(a,bc) print '( "Vp3 = (",3F10.3,")")', vector_prod(a,bc) contains function vector_prod(x,y) result(z) implicit none real, dimension(1:3), intent(in) :: x,y real, dimension(1:3) :: z z(1)=x(2)*y(3)-x(3)*y(2) z(2)=x(3)*y(1)-x(1)*y(3) z(3)=x(1)*y(2)-x(2)*y(1) end function vector_prod function scalar_prod(x,y) result(sp) implicit none real, dimension(1:3), intent(in) :: x,y real :: sp sp=x(1)*y(1)+x(2)*y(2)+x(3)*y(3) end function scalar_prod end
No ``intent”
Example: Triple products of scalar and vectors
Review of Contains
real, external :: vector_prod, scalar_prod はいらない
b x c a . (b x c) a x (b x c)
1.No declaration of type and attributes of internal function
2.Variables and arrays defined in the parent program are
effective in the child program and the same values are shared
3.When the same variable names as in the parent program are declared,
they are effective only in the child program and not shared.
4.Conatins statement is not allowed in the internal procedure
5.Referring other internal procedure from one internal procedure
is allowed when the two are in the same parent program
6. There must be ``subroutine, function“ in the end statement in
the contains program
Nagoya Institute of Technology
Recursive call
Subprogram calls itself (do not fall in the infinite loop)
recursive subroutine subroutine name(list of dummy arguments)
recursive function name (list of dummy arguments) result(variable names)
Specifying recursive procedure
must!
Nagoya Institute of Technology
Legendre polynomials
Chebyshev polynomials
Hermite polynomials
n=0
n=1
n=2
n=3
n=4
n=0
n=1
n=2
n=3
n=4
n=0
n=1 n=2
n=3
n=4
Nagoya Institute of Technology
program main implicit none integer :: n,i real :: x,y,p character(len=1) :: c(-25:25) print *,'What is the order of Polynomial, n?' read *,n print '( "Legendre Polynomial P(",i2,",x)")',n do i=-20,20 x=0.05*i ! dx=1/n=0.05 y=p(n,x) call presentation print '(f5.2,2x,f10.6,1x,51a1)',x,y,c end do contains subroutine presentation integer ::j if(i/=0) then c=' ' else c=(/('-',j=-25,25)/) end if c(-25)='I';c(0)='I';c(25)='I' c(nint(25*y))='*' end subroutine end
recursive function p(n,x) result(pnx) real :: pnx integer, intent(in) ::n real,intent(in) ::x if(n==0) then pnx=1.0 else if(n==1) then pnx=x else pnx=(2.0-1.0/n)*x*p(n-1,x) & -(1.0-1.0/n)*p(n-2,x) end if end function
Legendre polynomials
Quite often appears in the solution of partial diff. Eq.
Recurrence relation
Nagoya Institute of Technology
! Computation of special functions integer, parameter:: fun_kind=3 ! Choose type of special function ! fun_kind=1: Legendre, =2: Chebyshev, =3: Hermite real*8, parameter:: x_max=1.d0 Integer, parameter:: n_grid=50, n_order=4, k_write=2 character(len=1):: cn(0:9)=(/'0','1','2','3','4','5','6','7','8','9'/) character(len=2):: fn(1:3)=(/'p_','t_','h_'/) real*8 :: dx,x,y,fun integer :: i,n,n_n,n_p,n_extend select case (fun_kind) case(1) ; print *,' Legendre Polynomial P_n(x) ' case(2) ; print *,' Chebyshev Polynomial T_n(x) ' case(3) ; print *,' Hermite Polynomial H_n(x) ' end select dx=x_max/n_grid n_extend=1 if(fun_kind==3) n_extend=4 ! extend the x-domain for Hermite polynomial n_n=-n_grid*n_extend n_p= n_grid*n_extend do n=0,n_order write(6,'(/," n=",i2,/)') n open(10+n,file=fn(fun_kind)//cn(n)//'.dat') do i=n_n,n_p x=i*dx y=fun(fun_kind,n,x) write(10+n,'(1pe10.3, 2x, 1pe10.3)') x, y if(mod(i,k_write)==0) write(6,'(1pe10.3, 2x, 1pe10.3)') x,y end do end do end
Legendre, Chebyshev, Hermite polynomials
1/2
Nagoya Institute of Technology
recursive real*8 function fun(kind,n,x) result (sf) integer, intent(in) :: kind, n real*8, intent(in) :: x if(n==0) then sf=1.d0 else if(n==1) then select case(kind) case(1); sf=x case(2); sf=x case(3); sf=2.d0*x end select else select case(kind) case(1); sf=(2.d0-1.d0/n)*x*fun(kind,n-1,x)-(1-1.d0/n)*fun(kind,n-2,x) case(2); sf=2.d0*x*fun(kind,n-1,x)-fun(kind,n-2,x) case(3); sf=2.d0*x*fun(kind,n-1,x)-2.d0*(n-1)*fun(kind,n-2,x) end select end if end
2/2
Nagoya Institute of Technology
Report 4
1. To numerically integrate the following functions by using subroutine, external
function and recurrence procedure
2. To compare the numerical results with the analytical calculations
Report No.
ID no.
Name
Date Use Simpson’s formula
(1)
(2)
Use trapezoidal forumla