2014-03-01 118 views
1

我對C++非常陌生,所以請原諒我的無知。我正在使用Boost庫來執行一維優化。我正在使用brent_find_minima功能,並查看了文檔頁面here。但是對於輸入到brent_find_minima函數,還有另外一個函數f需要給出。向brent_find_minima添加額外的參數

使用它的示例顯示爲here,但它們的功能只包含一個參數。即double f(double x){...},如果你想提供f的附加參數,以便優化參數例如改變double f(double x, int y, int z){...}其中yz可以更改相同的功能f的結果x是否可以在brent_find_minima階段指定此項?

鑑於我對C++非常新,任何示例顯示如何完成/更改鏈接中給出的示例以接受多於1個參數將非常有幫助。

回答

2

如果你想傳遞的固定值Y,Z你可以只使用一個綁定表達式:

double f(double x, int y, int z) 
{ return (y*sin(x) + z + x * cos(x)); } 

brent_find_minima(std::bind(f, _1, 3, 4), 3.0, 4.0, 20); 

即通過3, 4y, z

如果情況並非如此,我不相信布倫特算法仍然是一個有效的方法。

看到它Live On Coliru

#include <iostream> 
#include <sstream> 
#include <string> 

#include <functional> // functional 
using namespace std::placeholders; 

#include <boost/math/tools/minima.hpp> 

double f(double x, int y, int z) 
{ return (y*sin(x) + z + x * cos(x)); } 

int main(int argc, char** argv) 
{ 
    typedef std::pair<double, double> Result; 
    // find a root of the function f in the interval x=[3.0, 4.0] with 20-bit precision 
    Result r2 = boost::math::tools::brent_find_minima(std::bind(f, _1, 3, 4), 3.0, 4.0, 20); 
    std::cout << "x=" << r2.first << " f=" << r2.second << std::endl; 
    return 0; 
} 

// output: 
// x=3.93516 f=-0.898333 
+0

以下是手動函數對象:http:// coliru。 stacked-crooked.com/a/cba30664291e366e – sehe

2

總是可以提供一個函數而不是函數。 在這種情況下,指定的函數會從brent_find_minimize函數調用一個參數。如果您想包括更多的參數,你需要寫一個函子是這樣的:

struct f 
{ 
    f(int y, int z) : _y(y), _z(z) { } 
    // you may need a copy constructor and operator= here too ... 

    double operator()(double x) 
    { 
     return _y*sin(x) + _z + x * cos(x); 
    } 
    int _y, _z; 
}; 

然後你可以將它傳遞這樣的:

Result r2 = boost::math::tools::brent_find_minima(f(10, 20), 3.0, 4.0, 20); 

希望這有助於。

+0

謝謝!你可以給一個完整的例子,說明如果你的f是'double f(double x,int y,int z){return(y * sin(x)+ z + x * cos }'...對不起......我對函子/構造函數/運算符等有點新,以及它可能與'std :: bind'方法有什麼不同? –

+0

@ h.l.m我在評論中添加了一個我的回答 – sehe

+1

我編輯了代碼。與使用std :: bind不同的是,函數也可以用於非C++ 11兼容編譯器。有關std :: bind的更多信息,請在此處查看參考資料:http://en.cppreference.com/w/cpp/utility/functional/bind – DNT