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 }