You are on page 1of 8

Fortran exercise

Francesco Battista
1

Corso di Calcolo Numerico


DIMA, Sapienza University of Rome, Italy

April 13, 2014

Francesco Battista

Fortran exercise

Generate File Name name.f90 code


1
2
3
4
5
6
7
8
9
10

! File: name_file.f90
! Gestire e creare una stringa corrispondende
! al nome di un file
PROGRAM name_file
IMPlICIT NONE
CHARACTER(30):: name
CHARACTER(1):: ver
CHARACTER(6):: time
CHARACTER(4):: ext
INTEGER :: it

11
12

it= 10

13
14
15
16
17

ext=.dat
ver=a
WRITE(time,(i6.6)) it
name = ver//time//ext

18
19

WRITE(*,*) Apro il file ,name

20
21
22

STOP
END PROGRAM name_file

Francesco Battista

Fortran exercise

Open and Read a file: read_file.f90 code


1
2
3
4
5
6
7
8
9

! File: name_file.f90
! Gestire e creare una stringa corrispondende
! al nome di un file
PROGRAM read_file
IMPlICIT NONE
CHARACTER(30):: name_file
CHARACTER(7):: ver
CHARACTER(4):: ext
REAL :: pi

10
11
12
13

ext=.dat
ver=input
name_file = trim(ver)//ext

14
15
16
17
18

WRITE(*,*) Apro il file ,name_file


OPEN(UNIT=1,FILE=name_file,STATUS=old,ACTION=read)
READ(1,*) pi
CLOSE(1)

19
20
21

WRITE(*,*) Il contenuto del file ,name_file, e , pi


WRITE(*,10) name_file, pi

22
23
24
25

10 FORMAT(Il contenuto del file ,A9, e, F7.4)


STOP
END PROGRAM read_file
Francesco Battista

Fortran exercise

Ordinary differential equation (ODE)

dy

= y
dx

y(0) = y0

x [0, 10]
x=0

solution
y(x) = y0 e x

needed parameter = 3 and y0 = 1


exercises: find the solution of the present ODE
1
2

at x = 10 and write it on the screen


from x = 0 to x = 10 and write it on the screen

Francesco Battista

Fortran exercise

Algorithm 1
START
READ
PARAMETERS

OK?

NO

YES
SET x
EVALUATE
y(x)
END
Francesco Battista

Fortran exercise

Open and Read a file: exact_sol.f90 code


1
2
3

PROGRAM main
IMPLICIT NONE
REAL :: y,x,alpha,y0

4
5
6
7
8

x=1.0
alpha=3.0
y0=1.0
CALL exact_sol(y,x,y0,alpha)

9
10

WRITE(*,*) La soluzione al tempo t=,x, e uguale a y=,y

11
12
13
14

STOP
END PROGRAM main
!_____________________________________________________________

15
16
17
18
19

SUBROUTINE exact_sol(y,x,y0,a)
IMPLICIT NONE
REAL,INTENT(IN):: y0,x,a
REAL,INTENT(OUT):: y

20
21

y = y0*exp(-x*a)

22
23
24

RETURN
END SUBROUTINE exact_sol
Francesco Battista

Fortran exercise

Algorithm 2
START
READ
PARAMETERS

NO

xmax>xmin?

YES
SET
Dx x=x0

EVALUATE
x=x+Dx

x>xmax?

END
Francesco Battista

Fortran exercise

Open and Read a file: exact_sol_time.f90 code


1
2
3
4
5
6

PROGRAM main
IMPLICIT NONE
INTEGER,PARAMETER :: Nx=10
INTEGER :: i
REAL :: y,x,alpha,y0
REAL :: Dx,x_max,x_min

7
8
9
10
11
12

x_max=2.
x_min=0.
Dx=(x_max-x_min)/(Nx+1)
alpha=3.0
y0=1.

13
14
15
16

do i=0,Nx
x=x_min+Dx*i
CALL exact_sol(y,x,y0,alpha)

17
18
19

WRITE(*,*) x,y
enddo

20
21

WRITE(*,*) Fine della simulazione

22
23
24
25

STOP
END PROGRAM main
!_____________________________________________________________
Francesco Battista

Fortran exercise

You might also like