Data type mismatch in fortran

孤街浪徒 提交于 2019-12-02 08:57:07

The problem is that f is not explicitely defined in your main program, therefore it is implicitly assumed to be of single precision, which is the type real(4) for gfortran.

I completely agree to the comment of High Performance Mark, that you really should use implicit none in all your fortran code, to make sure all object are explicitely declared. This way, you would have obtained a more appropriate error message about f not being explicitely defined.

Also, you could consider two more things:

  • Define your function within a module and import that module in the main program. It is a good practice to define all subroutines/functions within modules only, so that the compiler can make extra checks on number and type of the arguments, when you invoke the function.

  • You could (again in module) introduce a constant for the precicision and use it everywhere, where the kind of a real must be specified. Taking the example below, by changing only the line

    integer, parameter :: dp = kind(1.0d0)
    

    into

    integer, parameter :: dp = kind(1.0)
    

    you would change all your real variables from double to single precision. Also note the _dp suffix for the literal constants instead of the d0 suffix, which would automatically adjust their precision as well.

    module accuracy
      implicit none
    
      integer, parameter :: dp = kind(1.0d0)
    
    end module accuracy
    
    
    module myfunc
      use accuracy
      implicit none
    
    contains
    
      function f(n,x)
        integer :: n
        real(dp) :: x(n), f
        f = 0.5_dp * x(1)**5 + cos(x(2)) + log(x(3)) - sqrt(x(4))
      end function f
    
    end module myfunc
    
    
    program gradient
      use myfunc
      implicit none
    
      real(dp) :: x(n), xhup(n), xhdown(n), d(M), r(M), dfdxi, h0, h, gradf(n)
      :
    
    end program gradient
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!