« previous next»

4.1    External Functions

    Functions can be defined and accessed outside of the main code structure.  Functions are basically similar to subroutines (discussed in 4.2), just simpler.  Functions return either a number, array, logical result, or character array.  The FUNCTION option exists so you can create mathematical functions that are not explicitly defined (as ABS, SQRT, etc.) in the Fortran 90 library.  Once a function is defined it is used in the same way as any of the library functions.  Functions can only return one value or one array of values.  The basic structure for using and defining a function is as follows:

    PROGRAM name
    ...
    ...
    variable = functionname (argument_list1)
    ...
    ...
    END PROGRAM


    FUNCTION function_name(argument_list2)

    type declarations

    functionname = expression

    RETURN

    END FUNCTION

Argument_list1 and argument_list2 do not have to be the same, but they do have to contain the same number and type of variable.  If their names are different then argument_list1 is mapped to the values of argument_list2.

An example program using a function:

    PROGRAM testfunc

    IMPLICIT NONE

    REAL :: a, b, c, func

    a = 3.0
    b = 4.0

    c = func(a,b)

    END PROGRAM testfunc

    FUNCTION func(x,y)

    REAL :: func
    INTEGER, INTENT (IN) :: x, y

    func = x ** 2 + 2 * y

    END FUNCTION func

This program will take the values of a and b and input them into the function func(x,y) returning a value for c of 17.0. It is important to define the type for the function, in this case it is real (as seen by the definition "REAL :: func(x,y)").  You can also choose your function to be of type INTEGER, CHARACTER (as needed for the hmwk), or LOGICAL.

Tip: Use functions wisely! Innapropriate use may dramatically but unnecessarily increase the computational time. Consider the following example:

z = f(x)/(1.0 + f(x))

where f(x) is a REAL valued function that has been defined. Here, to compute z we will need two function evaluations, that is f is evaluated two times. But if we wrote:

y = f(x)
z = y/(1.0 + y)

we now need to evaluate f only once. This means that we decrease the computational time by a factor of two! This can be very significant if the function to be evaluated is "tough"...

« previous next»