2012-03-09 121 views
0

我用Fortran 90的優化求解所以,如果我想改變目標函數 我必須修改的主要文件,並以這種方式編寫的目標函數:Fortran中從文件讀取功能90

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 

我有一個很大的目標函數,所以我想從外部文件或至少子文件中調用這一行「f = x(1)** 2-x(2)+ 2 * x(3)」 。

這可能嗎? (我是Fortran中的新成員。)

我知道我可以用Python修改文件,但是我想在其他文件中執行此操作。

非常感謝!

+0

不太確定,你想從哪裏撥打電話? – haraldkl 2012-03-09 22:58:10

+0

不太確定:你想在編譯之前或之後修改函數嗎?在Fortran中,編譯後無法修改源文件。 – max 2012-03-11 11:25:02

回答

3

當然。使用:

include 'file.inc' 

包含來自外部文件的源代碼。

+0

謝謝,這工作! – 2012-03-12 22:27:18

2

我不知道如果這是你在找什麼,但:

的Fortran,您還可以通過周圍的子程序/功能名稱作爲實際參數子程序/函數調用。相應的僞參數必須具有「外部」屬性。

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 

當然,這個程序做無非呼叫FUNC1和FUNC2在晦澀的方式有用其他,但希望它說明了這一點。如果您正在尋找在編譯時轉出功能,那麼我認爲一個include "myfile"可能是清潔劑(只是切換哪個文件你包括在時間@AlejandroLL的建議)

2

您也可以嘗試在程序中使用模塊。有時當你將特殊變量傳遞給你的子程序/函數時,你需要爲它們編寫接口。使用模塊將改進您的程序結構,並且您將更加有效,並且所有接口都將自動生成。