2014-10-10 127 views
2

在fortran中,我有一個外部優化例程,它將輸入function f(x)作爲輸入,並返回起始點並返回局部最小值。例如,如果函數被調用最低:Fortran最小化帶附加參數的函數

minimum(f,x0,xopt) 

的問題是,我需要最小化功能取決於不屬於最小化過程的一部分,一些額外的參數:f(x,data)

我該如何解決這個問題。 在MATLAB我會用匿名函數

[email protected](x) f(x,data) 

minimum(g, x0, xopt) 

然而,正如我在Fortran 90的understant沒有匿名函數。

謝謝。

+0

羅Markus的書(http://www.amazon.co .uk/Modern-Fortran-Practice-Arjen-Markus/dp/1107603471/ref = sr_1_1?s = books&ie = UTF8&qid = 1412938088&sr = 1-1&keywords = arjen + Markus)涵蓋了這個主題。給自己一個副本,其餘的東西也是好東西。 – 2014-10-10 10:49:30

+0

參見http://stackoverflow.com/q/24127313/3157076 – francescalus 2014-10-12 11:57:32

回答

0

你有從MATLAB正確的想法,你可以創建另一個函數返回f的值,而封裝data。想到兩個選項。

如果data被固定在編譯時,可以使用它的模塊中包裹f

Module Foo 
    type(blah) :: data = ... 
    Contains 
     Real Function f(x) 
      ! data is visible here. 
     End Function f 
End Module Foo 

如果data是通過用戶輸入或計算多個動態,則可以定義一個返回功能dataf中調用它:

Real Function f(x) 
    ... 
    Type(blah), Save :: data 
    Logical, Save :: data_not_loaded = .True. 
    If data_not_loaded Then 
    data = load_data(...) 
    data_not_loaded = .False. 
    End If 
    ... 
End Function f 

取而代之的是load_data()功能,你也可以做一個類似註冊表的子程序,首先設置程序中較早的data的值,然後從f內檢索data。但是,f中的邏輯不會改變那麼多。

也可能有一種使用過程指針的方法,但我從來沒有在Fortran中使用該功能,所以我可能是錯的。

2

你不需要匿名函數。您的Matlab示例最終也不是匿名的,它的名稱爲g

的Fortran內部函數都是在這裏大量使用(2008年Fortran的功能,但在gfortran和ifort支持,在工作室的Solaris不支持):

call minimum(g, x0, xopt) 

contains 

    real function g(x) 
    real, intent(in) :: x 
    g = f(x,data) 
    end function 

end