I want to calculate a multivariable function func(x) and its gradient dfunc(x),
where x is a vector. The gradient dfunc(x) is calculated with finite
difference method. I defined two modules and a calling program as follows:
1. Mod_func: module to calculate the function values at x
2. Mod_dfunc: module to calculate the gradient at x. Since numerical finite
difference formula are used to obtain dfunc(x), dfunc(x) needs to call func(x).
3. drive: calling program
If dfunc is not included, and correspondingly not called from the calling
program(drive.f90), it works fine.
When dfunc is included, this causes compilation error:
$ gfortran -c func.f90 dfunc.f90 drive.f90
drive.f90:8.14:
real ::dfunc(ndim)
1
Error: Cannot change attributes of USE-associated symbol dfunc at (1)
The codes:
Module mod_func
! Purpose: To calculate multivariable function func(x), x is a vector
Contains
FUNCTION func(x)
IMPLICIT NONE
REAL, DIMENSION(:), INTENT(IN) :: x
REAL :: func
integer::i,n
n=size(x)
func=0
do i=1,n ! a simple multivariable function: func(x) = x1**2 + x2**2 + ...
func= func+ x(i)**2
end do
END FUNCTION func
End module mod_func
Module mod_dfunc
! Purpose: To calculate gradient at x by finite difference, where x is a vector
Contains
FUNCTION dfunc(x)
use mod_func ! To calculate dfunc(x), we need
! function values func(x) and func(x+äx)
! ä is a small scalar
implicit none
REAL, DIMENSION(:), INTENT(IN) :: x
REAL, DIMENSION(size(x)) :: dfunc
real, dimension(:),allocatable:: e ! e is the unit vector
real :: del ! del ==> ä
integer:: i,n
del=sqrt(epsilon(x(1)))
n=size(x)
allocate(e(n))
do i=1,n
e=0.
e(i)=1.
!central difference formula
dfunc(i)=(func(x+del*e) - func(x-del*e))/(2.*del)
end do
deallocate(e)
END FUNCTION dfunc
End module mod_dfunc
program drive
use mod_func
use mod_dfunc
implicit none
integer,parameter::ndim=2
real :: x(ndim) ! 2 variables, (x1,x2)
real ::func
real ::dfunc(ndim)
x=(/1.0,3./)
write(*,*) 'x:',x
write(*,*) 'function value:',func(x)
write(*,*) 'function gradiet:',dfunc(x)
end program drive
--
Summary: compilation error with function array
Product: gcc
Version: 4.4.3
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: fortran
AssignedTo: unassigned at gcc dot gnu dot org
ReportedBy: yyxt at hotmail dot com
GCC build triplet: build=x86_64-linux-gnu
GCC host triplet: host=x86_64-linux-gnu
GCC target triplet: Target: x86_64-linux-gnu
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=44344