Secant method
From LiteratePrograms
Secant method was developed from Newton Raphson method which improved in derivative.
Secant method use this derivative:
g'(x) = d / dx(x − f(x) / f'(x))
To know the root of a math equation, use this C language source code:
<<Read data from input>>= printf("Initial Value = "); scanf("%f",&x0); printf("Second Value = "); scanf("%f",&x1); printf("Tolerance/Error = "); scanf("%f",&tol); printf("Maximum iteration number = "); scanf("%d",&max_iter);
During iteration, the next value in the series is stored in xb; the current fault is the absolute of the difference between xb and x0. Iteration continues until we give up (the maximum number of iterations has been exceeded) or the result converges to within tolerance.
<<Iterate until we have a result>>= printf("It. x f(x) epsilon\n"); do { float xb = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0)); epsilon = fabs(xb - x0); x0 = x1; x1 = xb; it++; printf("%3d %8.5f %8.5f %8.14e\n", it, xb, f(xb), epsilon); } while(it <= max_iter && epsilon > tol);
<<Report convergence of failure>>= if (epsilon <= tol) { printf("Tolerance accepted\n"); printf("Current Result = %g\n", x1); } else printf("Tolerance not accepted\n");
An equation is plugged in as a function f(x)
<<Equation to be solved>>= float f(float x) { return 1 / x * exp(-500 / x) - 11.2e-9; }
<<secantmethod.c>>= /* Find root with Secant Method * Written by Agung Sudrajat S (Indonesia, 2010, Bandung Institute of Technology) */ #include <stdio.h> #include <math.h> Equation to be solved int main() { int it = 0; float epsilon = 0; /* Variables: x0=initial value tol=tolerance, error max_iter=number of max iterations */ float x0, x1, tol; int max_iter; Read data from input Iterate until we have a result Report convergence of failure return 0; }
This is the simple code that has been tested in Dev-C++ program (you can download it for free, just search in your web).
Good luck...
Written by Agung Sudrajat Supriatna, Bandung Institute of Technology, Indonesia.
Download code |