Friday, July 20, 2012

C Program for Secant Method


/*-*Secant Method*-*/

#include<stdio.h>

#include<conio.h>

#include<math.h>

#include<alloc.h>

#include<process.h>

float value(float);

float **e,n;

void main()

{

int i,p,it=50;

float v,xo,es,s=0,x1,ea,x_1;

char ch;

clrscr();

printf("Enter Degree of the Equation\n");

scanf("%f",&n);

puts("-------------------------------------------------");

e=(float**)malloc(((n+1)*2)*sizeof(float));

printf("Enter coeff.in decreasing order of Degree\n");

for(i=0,p=n;i<=n;i++,p--)

{

scanf("%f",&e[i][0]);

e[i][1]=p;

}

puts("-------------------------------------------------");

printf("Enter Value of X-1,X0\n");

scanf("%f %f",&x_1,&xo);

puts("------------------------------------------------");

printf("What would You Like to enter Es or Sig.fig or Iteration =>E/S/I");

ch=getche();

if(ch=='E'||ch=='e')

{

printf("\nEnter value of Es\n");

scanf("%d",&es);

}

else if(ch=='s'||ch=='S')

{

printf("\nEnter number of Sig. figure\n");

scanf("%d",s);

es=0.5*pow(10,(s-2));

}

else

{

printf("\nEnter no. of Iteration\n");

scanf("%d",&it);

}

puts("------------------------------------------------");

i=0;

printf("Iteration \tXi\t\tEa");

while(1)

{

i++;

x1=xo-(value(xo)*(x_1-xo))/(value(x_1)-value(xo));

ea=(x1-xo)*100/x1;

if(ea<0)

ea=ea*(-1);

if(ea<es||value(x1)==0||i==it)

{

printf("\n%3d\t\t%5.6f\t%5.4f",i,x1,ea);

puts("\n---------------------------------------------");

getch();

exit(0);

}

printf("\n%3d\t\t%5.6f\t%5.4f",i,x1,ea);

x_1=xo;

xo=x1;

}




}

float value(float x)

{

int i;

float s=0;

for(i=0;i<=n;i++)

{

s=s+e[i][0]*pow(x,e[i][1]);

}

return s;

}

















































Output of Program:-

Enter Degree of the Equation

3

-------------------------------------------------

Enter coeff.in decreasing order of Degree

1 -6 11 -6.1

-------------------------------------------------

Enter Value of X-1,X0

2.5 3.5

------------------------------------------------

What would You Like to enter Es or Sig.fig or Iteration =>E/S/Ii

Enter no. of Iteration

3

------------------------------------------------

Iteration Xi Ea

1 2.711111 29.0984

2 2.871090 5.5721

3 3.221925 10.8890

---------------------------------------------

















No comments:

Post a Comment