使用虚拟容器的方法实现二分法求解方程的根(1)

 1  #include <iostream>
2 #include <iterator>
3 #include <algorithm>
4 #include <functional>
5 #include <cmath>
6 #include "virtual_iterator.h"
7 template< class Equation,long number=15 > struct Method
8 {
9 typedef Equation equation_type;
10 typedef std::pair<double,double> element_type;
11 struct Generator:std::unary_function<const size_t&,element_type&>
12 {
13 element_type&operator()(const size_t&i)
14 {
15 Method::process(Method::value());
16 return Method::value();
17 }
18 };
19 struct Predicate:std::unary_function<const element_type&,bool>
20 {
21 bool operator()(const element_type&e)
22 {
23 const double&eps = precision(number);
24 return fabs( e.first - e.second ) < eps;
25 }
26 };
27 public:
28 static void range(const double&a,const double&b)
29 {
30 value() = std::make_pair(a,b);
31 }
32 private:
33 static element_type&value()
34 {
35 static element_type _value;
36 return _value;
37 }
38 static void process(element_type&e)
39 {
40 Equation eqn;
41 const double&eps = precision(number);
42 double&a=e.first;
43 double&b=e.second;
44 double x,fa,fb,fmid;
45 fa=eqn(a); fb=eqn(b);
46 if(fabs(fa)<=eps) b = a;
47 else if(fabs(fb)<=eps) a = b;
48 else{
49 fmid=eqn(x=(a+b)/2);
50 if(fmid==0){ a=x,b=x; }
51 else if(fmid*fa<0){ b=(a+b)/2; }
52 else if(fmid*fb<0){ a=(a+b)/2; }
53 }
54 }
55 static double precision(const long&n)
56 {
57 static bool evalued = false;
58 static double _eps = 1.0;
59 if(!evalued){
60 long i=0; for(i=0;i<n;i++)_eps *= 0.1;
61 evalued = true;
62 }
63 return _eps;
64 }
65 };
66 struct Equation:std::unary_function<const double&,double>
67 {
68 double operator()(const double&x)
69 {
70 return x*x - 2;
71 }
72 };
73
74 int main()
75 {
76 std::cout.precision(20);
77 typedef Method<Equation,15> M;
78 typedef virtual_iterator<M::element_type,M::Generator> SOLVE;
79 {
80 M::range(1.0,2.0);//设置根所在的区间
81 SOLVE begin(1),end(10000),root;
82 root = std::find_if(begin,end,M::Predicate());
83 std::cout << "迭代次数:[" << static_cast<const size_t&>(root) << "]" << std::endl;
84 std::cout << "左根:[" << (*root).first << "]" << std::endl;
85 std::cout << "右根:[" << (*root).second << "]" << std::endl;
86 }
87 {
88 M::range(-1.0,-2.0);//设置根所在的区间
89 SOLVE begin(1),end(10000),root;
90 root = std::find_if(begin,end,M::Predicate());
91 std::cout << "迭代次数:[" << static_cast<const size_t&>(root) << "]" << std::endl;
92 std::cout << "左根:[" << (*root).first << "]" << std::endl;
93 std::cout << "右根:[" << (*root).second << "]" << std::endl;
94 }
95 return 0;
96 }
97
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值