Sunday, 17 March 2013

C Program for Secant Method


#include<stdio.h>
#include<conio.h>
#include<math.h>
#define E 0.0001
#define F(x) x*x - 4*x - 10
void main(){
  float x1,x2,x3,f1,f2,t;
  clrscr();
  printf("\nEnter the value of x1: ");
  scanf("%f",&x1);
  printf("\nEnter the value of x2: ");
  scanf("%f",&x2);
  printf("\n______________________________________________\n");
  printf("\n    x1\t  x2\t  x3\t     f(x1)\t f(x2)");
  printf("\n______________________________________________\n");
  do{
                f1=F(x1);
                f2=F(x2);
                x3=x2-((f2*(x2-x1))/(f2-f1));
                printf("\n%f   %f   %f   %f   %f",x1,x2,x3,f1,f2);
                x1=x2;
                x2=x3;
                                if(f2<0)
                                                t=fabs(f2);
                                else
                                                t=f2;
  }while(t > E);

printf("\n______________________________________________\n");
printf("\n\nApp.root = %f",x3);
getch();
}

Sample Output:

Enter the value of x1: 4
Enter the value of x2: 2
-----------------------------------------------
x0            x1        x2           f(x0)           f(x1)
-----------------------------------------------
4.000   2.000   9.0000   -10.000    -14.000
2.000   9.000   4.0000   -14.000    35.000
9.000   4.000   5.1111   35.000     -10.000
4.000   5.111   5.9565   -10.000    -4.321
5.111   5.957   5.7225   -4.321      1.654
5.957   5.722   5.7411   1.654       -0.143
5.722   5.741   5.7417   -0.143     -0.004
5.741   5.742   5.7417   -0.004      0.000
-----------------------------------------------

App.root = 5.741657

©Dixit Bhatta 2013

No comments:

Post a Comment

Was this post helpful? Ask any questions you have, I will try to answer them for you.