Sunday 20 March 2016

Solve the Secent method equation using C

Assume we need to find a root of the equation f (x) = 0, called α. Consider the graph of the function f (x) and two initial estimates of the root, x0 and x1. The two points (x0,f (x0)) and (x1,f (x1)) on the graph of f (x) determine a straight line, called a secant line which can be viewed as an approximation to the graph. The point x2 where this secant line crosses the x axis is then an approximation for the root α.

This is the same idea as in Newton’s method, where the tangent line has been approximated by a secant line.

The equation of the secant line will be given by
         
y = f(x1)+(x−x1) * (f(x1)−f(x0) /  x1−x0)
so

x2 = x1−f(x1)  * (x1−x0 / f(x1) − f(x0))

Then take x1 and x2 as the next two estimates and continue the procedure. The general iteration will be given by
xn+1 =  xn−f(xn) * (xn− xn-1 / f(xn) − f(xn-1))

and so on.

Advantages and disadvantages:

  1. The error decreases slowly at first but then rapidly after a few iterations.
  2. The secant method is slower than Newton’s method but faster than the bisection method.
  3. Each iteration of Newton’s method requires two function evaluations, while the secant method requires only one
  4. The secant method does not require differentiation.


                                                                                            
Example Code:

equation x2-5
root between 2 and 3
File name : newton.c

#include<stdio.h> #include<conio.h> #include<math.h> #define E 0.0001 float f(float x) { return (x*x)-5; } void main() { float x0,x1,x2,fx0,fx1,fx2; intctr=0; clrscr(); printf("Enter value of X0:"); scanf("%f",&x0); printf("Enter value of X1:"); scanf("%f",&x1); clrscr(); printf("\n---------------------------------------------------------"); printf("\n| SECENT METHOD |"); printf("\n---------------------------------------------------------"); printf("\n| NO\t| x0\t| f(x0)\t| x1\t| f(x1)\t| x2\t| f(x2) |"); printf("\n---------------------------------------------------------"); do { fx0=fx1=fx2=0; fx0=f(x0); fx1=f(x1); x2=((x0*fx1)-(x1*fx0))/(fx1-fx0); fx2=f(x2); printf("\n%d\t|%.3f\t|%.3f\t|%.3f\t|%.3f\t|%.3f\t|%.3f",ctr+1,x0,fx0,x1,fx1,x2,fx2); x0=x1; fx0=fx1; x1=x2; fx1=fx2; ctr++; }while(fabs(fx2)>=E); printf("\n\nx2 : %.4f",x2); getch(); }

No comments:

Post a Comment

Thanks to comment our blog. i will contact you as soon as possible

Create Thumbnail in Video in Spring and ffmpeg

import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.jcodec.api.Fr...