弦截法求方程根

THE SECANT METHOD

In numerical analysis, the secant method is a root-finding algorithm that uses a succession of roots of secant lines to better approximate a root of a function f. The secant method can be thought of as a finite difference approximation of Newton's method. However, the method was developed independently of Newton's method, and predated the latter by over 3,000 years.

 1 /*
 2  * =====================================================================================
 3  *
 4  *       Filename:  secant_method.cc
 5  *
 6  *    Description:  secant method
 7  *
 8  *        Version:  1.0
 9  *        Created:  2015年07月16日 13时53分26秒
10  *       Revision:  none
11  *       Compiler:  g++
12  *
13  *         Author:  YOUR NAME (), 
14  *   Organization:  
15  *
16  * =====================================================================================
17  */
18 #include <iostream>
19 #include <cmath>
20 using namespace std;
21 
22 double f(double x)                              //所要求解的函数公式
23 {
24     return x*x*x - 3*x -1;
25 }
26 
27 double point(double a, double b)                //求解弦与x轴的交点
28 {
29     return (a*f(b) - b*f(a))/(f(b) - f(a));
30 }
31 
32 double root(double a, double b)                 //用弦截法求方程在[a, b]区间的根
33 {
34     double x, y, y1;
35     y1 = f(a);
36     do {
37         x = point(a, b);                        //求交点x坐标
38         y = f(x);                               //求y
39         if (y*y1 > 0)
40             y1 = y, a = x;
41         else
42             b = x;
43     }while (fabs(y) >= 0.000001);               //计算精密度
44     return x;
45 }
46 
47 int main()
48 {
49     double a, b;
50     cin>>a>>b;
51     cout<<"root = "<<root(a, b)<<endl;
52     return 0;
53 }

 

posted @ 2015-07-16 14:20  berthua  阅读(1138)  评论(0编辑  收藏  举报