We define a module Coeff which declares the order n of the approximation; the maximal order allowed n_max=10 and a vector b of coefficients for the Taylor polynomial. Note that, in the definition, we include specifically the range to be 0:n_max; this means that b will contain n_max+1 elements, indexed from 0 to n_max.
module coeff integer :: n integer, parameter :: n_max = 10 real, dimension(0:n_max) :: b end module coeff program approx use coeff implicit none real :: x integer :: i external taylor_exp real, external :: eval ! print*, "please input order (n <= 10)" read*, n n = min(n, n_max) call taylor_exp ! do i=-3,3 x= 2.0**i print*, x,") exp=",exp(x), & "; taylor=", eval(x) end do end program approx subroutine taylor_exp ! calculate the first n coefficients ! in the taylor approx. of exp use coeff implicit none integer :: i b(0) = 1.0 do i=1,n b(i) = b(i-1)/real(i) end do end subroutine taylor_exp real function eval(x) ! evaluate the order n ! polyn. with coefficients b(i) use coeff implicit none real, intent(in) :: x integer :: i eval = b(n) do i = n-1,0,-1 eval = b(i)+x*eval end do end function eval
The subroutine Taylor_exp USEs the module Coeff. As a consequence, it has access to all three global variables n, n_max and b. Note that this subroutine has no arguments, which is legal in F90, but does all the communication with the ouside world via the global variables in the module Coeff. Taylor_exp calculates the first n+1 coefficients in the Taylor series for the exponential function, and stores them in b(0) through b(n).
The function Eval has just one input argument, x.
It also USEs the module
Coeff, hence it
``sees''n, n_max and b.
The function evaluates the value of the polynomial
The main program also USEs Eval. Because of this, the variables in Eval exist as long as the program runs; they are effectively static variables (we will discussed in the future about this). The subroutine Taylor_exp, the function Eval and the main program all have access to n, n_max and b; any of them can read and write any of these variables; in this sense, n, n_max and b are called global variables. We say that the scope of n, n_max and b includes the main program, the subroutine and the function.
The main program reads in the desired order of approximation n; then, sets it to n_max if it is larger than this maximal value. When called, the subroutine Taylor_exp fills in b(0) ... b(n) with the coefficients of the n Taylor polynomial. Finally, Eval is called several times, with different arguments, and the results of the intrinsic function and this approximation are printed together, for comparison. Note that, once the coefficients b(0) ... b(n) have been calculated and stored, they can be subsequently used to obtain any number of approximate values Eval(x).