Lesson Topics | |
Statement Functions | Do While Loops |
Continuation Lines | Sign Function |
View Demos | Download Demos |
# 1 # 2 # 3 # 4 # 5 # 6 | # 1 # 2 # 3 # 4 # 5 # 6 |
Main Fortran Page |
You may replace f with any name you like for your function, and x, y, z, … with your own variable names. Instead of formula type the formula for your function.
Examples :
area(r) = pi * r * r |
vol(r,h) = pi * r * r * h |
f(x,y,z) = sqrt(x / y) * cos(z) |
You should declare a type for the function in a declaration statement. Here is a program using a statement function, named "area", to compute areas of circles; the program computes in double precision the area of an annulus of inner radius a and outer radius b:
program annulus | |
double precision r, area, pi, a, b | |
parameter (pi = 3.1415926535897932D0) | |
area(r) = pi * r * r | |
print *, "Enter the inner and outer radii of the annulus: " | |
read *, a, b | |
write (*,10) "The area of the annulus is ", area(b) - area(a) | |
10 | format (a,f25.15) |
end |
In the type declaration statement just include the name of the function - do not include the parentheses or the function variables.
Observe that variables plugged into the function need not be the same variables used in defining the function.
It is possible to use a previous statement function in the definition of another. In the above program, for example, we have already defined the function area(r), so we could define further a second function "annarea", giving the area of the annulus as
But this second function definition must appear later in the program than the first one.
Example :
det = a(1,1) * a(2,2) * a(3,3) + a(1,2) * a(2,3) * a(3,1) | |
& | + a(2,1) * a(3,2) * a(1,3) - a(3,1) * a(2,2) * a(1,3) |
& | - a(2,1) * a(1,2) * a(3,3) - a(1,1) * a(3,2) * a(2,3) |
N = 1 | | | N = 1 | |||
S = 0 | | | S = 0 | |||
do while (N .le. 10) | | | do 5 while (N .le. 10) | |||
S = S + N ** 2 | | | S = S + N ** 2 | |||
N = N + 1 | | | N = N + 1 | |||
end do | | | 5 | continue |
CASE 1: If y ≥ 0 then | ||
sign(x,y) = abs(x) , | ||
CASE 2: If y < 0 then | ||
sign(x,y) = - abs(x) . |
The practical effect is that sign(x,y) has the same absolute value as x, but it has the same sign as y; thus the sign of y is transferred to x. (The case y = 0 is a little special - it gives sign(x,y) always a plus sign.)
Examples :
The variables x and y in sign(x,y) may be integers or real numbers, and either single or double precision. (And x and y may even be of different types.)
If we substitute x = 1 in the sign transfer function, we get the sign of y; that is,
CASE 1: If y ≥ 0 then | ||
sign(1,y) = 1 , | ||
CASE 2: If y < 0 then | ||
sign(1,y) = - 1 . |
Thus, sign(1,y) in Fortran is essentially the same as the function SGN(y) in Basic (except when y = 0, when the Fortran value is + 1 but the Basic value is 0).