返回顶部

收藏

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;
}

标签:C++,切割线算法

收藏

0人收藏

支持

0

反对

0