Implementation of Secant Method written in C++.
IN -3 -1 0.0000001 Out X: -3 f(x): 2 X: -2 f(x): -1 X: -3 f(x): 2 X: -2.33333 f(x): -0.222222 X: -2.4 f(x): -0.04 X: -2.41463 f(x): 0.00118977 X: -2.41421 f(x): -6.00729e-06
// ? 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net #include <iostream> #include <math.h> using namespace std; static double function(double x); int main() { double xn1; //x_(n - 1) double xn; //x_n double x; double precision; cout << "Enter beginning of interval: "; cin >> xn1; cout << "Enter end of interval: "; cin >> xn; cout << "Enter precision of method: "; cin >> precision; if (function(xn1) * function(xn) > 0.0f) { cout << "Function has same signs at ends of interval"; return -1; } x = xn1; while (abs(function(x)) > precision) { cout << "X: " << x << " f(x): " << function(x) << endl; x = xn - ((function(xn) * (xn - xn1)) / (function(xn) - function(xn1))); xn1 = xn; xn = x; } int a; cin >> a; //Wait before exiting return 0; } static double function(double x) //x^2 + 2x -1 { return x * (x + 2) - 1; }
C++ Secant Method