//
//本文假设你已经熟悉自定义STL兼容游标的方法,如果不熟悉自定义STL兼容游标的方法可以参见
//本人的“自定义STL游标实现虚拟容器”的文章。
#include <iostream>
#include <iterator>
#include <algorithm>
#include <cmath>
//
template<class T,class EQUATION>
class solve_iterator:public std::iterator<std::forward_iterator_tag,T>
{
public:
solve_iterator(const size_t&i,EQUATION eqn,T&a,T&b,const T&eps)
:_i(i),_eqn(eqn),_a(a),_b(b),_eps(eps){}
solve_iterator(const size_t&i,solve_iterator const&it)
:_i(i),_eqn(it._eqn),_a(it._a),_b(it._b),_eps(it._eps){}
solve_iterator(solve_iterator const&it)
:_i(it._i),_eqn(it._eqn),_a(it._a),_b(it._b),_eps(it._eps){}
solve_iterator&operator=(solve_iterator const&it)
{ if(&it!=this){_i=it._i;_eqn=it._eqn;_a=it._a;_b=it._b;_eps=it._eps;}return*this; }
size_t& operator*(){return _i;}
const size_t& operator++()
{ process(); _i++;return _i; }
bool operator==(const solve_iterator<T,EQUATION>& other) const
{ return _i == other._i; }
bool operator!=(const solve_iterator<T,EQUATION>& other) const
{ return _i != other._i; }
bool operator()(const T&i)
{ return fabs(_a - _b)<=_eps; }
private:
void process()
{
T x,fa,fb,fmid;
fa=(*_eqn)(_a); fb=(*_eqn)(_b);
if(fabs(fa)<=_eps) _b = _a;
else if(fabs(fb)<=_eps) _a = _b;
else{
fmid=(*_eqn)(x=(_a+_b)/2);
if(fmid==0){ _a=x,_b=x; }
else if(fmid*fa<0){ _b=(_a+_b)/2; }
else if(fmid*fb<0){ _a=(_a+_b)/2; }
}
}
private:
size_t _i;
T _eps;
EQUATION _eqn;
T &_a,&_b;
};
//
//下面是测试代码:
int main()
{
struct X{
static double f1(const double&x){return x*x-1;}
static double f2(const double&x){return x*x-2;}
};
typedef solve_iterator<double,double(*)(const double&x)> SOLVE;
std::cout.precision(20);
{
double a=0,b=2;
SOLVE begin(0,X::f1,a,b,1e-8),end(10000,begin),root(begin);
root=std::find_if(begin,end,root);
std::cout << "迭代次数:[" <<*root<<"] a=[" << a << "] b=[" << b << "]" << std::endl;
}
{
double a=0,b=2;
SOLVE begin(0,X::f2,a,b,1e-15),end(10000,begin),root(begin);
root=std::find_if(begin,end,root);
std::cout << "迭代次数:[" <<*root<<"] a=[" << a << "] b=[" << b << "]" << std::endl;
}
return 0;
}
//运行结果如下:
/*******************************************************************************
迭代次数:[1] a=[1] b=[1]
迭代次数:[51] a=[1.4142135623730949] b=[1.4142135623730958]
*******************************************************************************/
自定义STL游标实现二分法求解方程的根
最新推荐文章于 2023-05-09 14:23:58 发布