Reading function from a file in Fortran 90

牧云@^-^@ 提交于 2019-12-12 05:10:18

问题


I have an optimization solver in Fortran 90. So, if I want to change the objective function I have to modified the main file and write the objective function in this way:

  subroutine fobj(n,x,f)
    implicit none
    integer :: n
    real(8) :: f
    real(8) :: x(n)
    intent(in ) :: n,x
    intent(out) :: f
    !OBJECTIVE FUNCTION
    f = x(1)**2-x(2)+2*x(3)
   end subroutine fobj

I have a big objective function, so I want to call this line "f = x(1)**2-x(2)+2*x(3)" from an external file or at least the subrutine.

Is that possible? (I'm new in Fortran.)

I know that I can modified the file with Python, but I want to do it in other file.

Thanks a lot!


回答1:


Sure. Use:

include 'file.inc'

to include source code from an external file.




回答2:


I'm not sure if this is what you're looking for, but:

Fortran also allows you to pass subroutine/function names around as actual arguments to subroutine/function calls. The corresponding dummy arguments must have the "external" attribute.

subroutine fobj(n,x,f,func)
  implicit none
  integer :: n
  real(8),external :: func
  real(8) :: f
  real(8) :: x(n)
  intent(in ) :: n,x
  intent(out) :: f
  !OBJECTIVE FUNCTION
  f=func(x,n)
end subroutine fobj

function func1(x,n)
  implicit none
  real(8) func1
  integer n
  real(8) :: f,x(n)
  f = x(1)**2-x(2)+2*x(3)
end function  func1

function func2(x,n)
  implicit none
  real(8) func2
  integer n
  real(8) :: f,x(n)
  f = x(1)**2+x(2)+2*x(3)
end function func2

program main
  real(8),external :: func1,func2
  real(8),allocatable :: x(:)
  real(8) :: f
  integer n
  n=50

  allocate(x(n))  
  x=10.  !Set X to a known value
  call fobj(n,x,f,func1) !Call func1
  print*,f  !10**2-10+2*10 = 110
  x=10.  !Reset X ... just to make sure there is no funny business in func1,func2
  call fobj(n,x,f,func2) !Call func2
  print*,f  !10**2+10+2*10 = 130
  deallocate(x)

end program main

Of course, this program does nothing useful other than call func1 and func2 in obscure ways, but hopefully it illustrates the point. If you're looking to switch out the function at compile-time, then I think a include "myfile" is probably cleaner (just switching which file you're including at the time as suggested by @AlejandroLL)




回答3:


You might also try to use Modules in your program. Sometimes when you pass special variables to your subroutines/functions you need to write interfaces for them. Using modules will improve your program structure and you'll be more effective and all interfaces would be generated automatically.



来源:https://stackoverflow.com/questions/9640657/reading-function-from-a-file-in-fortran-90

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!