ページ 11

関数の変数

Posted: 2014年4月05日(土) 01:49
by 591
BOOSTの2分法を用いて、方程式を解きたいと思っています。
以下のコードは、上手くいく例です。
1変数関数fを定義して、BOOSTに持っていってあげれば、方程式f=0を解くことができます。

今、関数fの中で定義されている定数cを、int main関数の中で定義したいと思っています。
すなわち、
double f(double x, int c) return c + 13/(1.0+x);
int main()
{
int c = 5;
.
.
}
としたいわけです。
ここで問題があります。関数fが見かけ上2変数関数になってしまい、BOOSTに持っていけなくなってしまいました。
見かけ上2変数関数ですが、実質は1変数関数なので、
以下のコードのようにBOOSTで計算できるはずだと思っています。

この問題を解決できる上手いやり方があれば、ぜひ教えていただきたいと思っています。
よろしくお願いいたします。

コード:

#include <iostream>
#include <math.h>
#include <boost/math/tools/roots.hpp>
using namespace std;
using namespace boost::math::tools;
double f(double x){
	
	const double c = -5.;
	return c + 13/(1.0+x);
}

bool tol(double low, double high)
       { return fabs(high - low) < .00001; }

int main()
{
	std::pair<double, double> range;
     range = bisect(f, 0., 10., tol);
	cout<<range.first<<endl;
     cout<<range.second<<endl;
	
	return 0;
}

Re: 関数の変数

Posted: 2014年4月05日(土) 08:26
by h2so5
boost::bindを使ってみてはどうでしょう。

http://www.kmonos.net/alang/boost/classes/bind.html
http://melpon.org/wandbox/permlink/0nL8nb6eTmrz8qGt

コード:

#include <iostream>
#include <math.h>
#include <boost/math/tools/roots.hpp>
#include <boost/bind.hpp>

using namespace std;
using namespace boost::math::tools;

double f(double x, int c){
    return c + 13/(1.0+x);
}
 
bool tol(double low, double high)
       { return fabs(high - low) < .00001; }
 
int main()
{
    int c = -5;
    std::pair<double, double> range;
    range = bisect(boost::bind(f, _1, c), 0., 10., tol);
    cout<<range.first<<endl;
    cout<<range.second<<endl;
    
    return 0;
}

Re: 関数の変数

Posted: 2014年4月05日(土) 10:10
by 591
h2so5さん
ありがとうございました。
boost::bind、大変助かりました。