# C++ 切割线算法

```/*
* File:   main.cpp
* Author: Bangonkali
*
* Created on March 27, 2012, 10:54 PM
*
* 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 3000 years. http://en.wikipedia.org/wiki/Secant_method

*/
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <limits.h> // max num of iterations -> ULONG_MAX

using namespace std;

double f(double x = 0) {
// this is the function to find the root of

// f(x) = (x+2)(x+2)(x+2); roots = -2;

return (x*x*x) + (6*x*x) + (12*x) + 8;
}

double error(double a, double b) {
return abs(((abs(a - b))/(b))*100);
}

/*
*
*/
int main(int argc, char** argv) {
double x1 = 10; // upperbound bound

double x0 = -10; // lower bound

double x = 0; // next bound

double err = 0; // relative error

unsigned long i;
for (i = 0; i < ULONG_MAX; i++) {
err = error(x0, x1);
if (err <= 1e-12) {
break;
}
x = x1 - (f(x1) * ((x1 - x0) / (f(x1) - f(x0))));
// cout << "err(" << x0 << ", " << x1 << "): " << err << endl;

x0 = x1; // move x1 to x0

x1 = x; // move x to x1

}

cout << "iterations: " << i << endl;
cout << "root: " << x1 << endl;
cout << "error: " << err << endl;
cout << "try root: f(x) = " << f(x1) << endl;
return 0;
}

```

0人收藏

0

0

1. owensss 发表 2014-11-25 03:12:18 优雅地同时遍历多个容器
2. neilxp 发表 2012-04-24 06:30:21 C++ Boost智能指针小测
3. dianlujitao 发表 2014-10-17 13:56:48 POJ 1611 The Suspects
4. 博主 发表 2012-07-29 00:00:00 c++ inline
5. 博主 发表 2013-01-27 00:00:00 C++11 和 C++98 的 ABI 兼容性
6. root 发表 2015-05-02 06:04:01 关于C++引用的一些注意点
7. jeffchen 发表 2014-01-06 10:21:51 重读程序员修炼之道
8. oldim 发表 2014-08-26 14:33:53 intel c++ 高性能运算工具
9. 风清天朗 发表 2015-05-05 03:56:40 [日积月累]C/C++可变参数函数的实现(转载)
10. lvfuyu 发表 2015-04-18 09:13:32 [hihocoder]二分查找
11. bbiao 发表 2014-07-03 13:06:18 gdb中dump一段内存
12. 姚 广远 发表 2015-04-13 00:56:19 在引用freetype2的头文件时产生’generic’错误