10 Ağustos 2007 Cuma

Bisection Method (Numerical Methods)

/* --------------------------------------------------- */
/* ### Bisection Method (Numerical Methods ) ### */
/* --------------------------------------------------- */
#include<stdio.h>
#include<conio.h>
/* A Power Calculating Function */
/* It accepts a floating base */
/* and an Integer Exponent. */
double pow(base,exponent)
double base;
int exponent;
{
double value=1.0;
int c;
for(c=0;c<exponent;c++)
{
value=value*base;
}
return value;
}
/* A function that calculates the value of a polynomial */
/* Expression having a single variable. The three */
/* parameters are the Degree of the Equation, the value */
/* of the variable and an array containing the */
/* coefficients with the subscript(position) of the array */
/* corresponding to the power of the variable. */
float polynomial(degree,x,coeff)
int degree;
float x;
float coeff[];
{
int c=0;
float ans=0.0;
for(c=0;c<=degree;c++)
{
ans=ans+(coeff[c]*pow(x,c));
}
return ans;
}
/* A function that rounds off a given number to */
/* the desired number of decimal places. */
float roundoff(value,accuracy)
float value;
int accuracy;
{
float tempd=0.0;
int tempi=0;
tempd=value*(pow(10.0,accuracy+1));
tempi=tempd;
if(tempi%10>=5)
{
tempd=tempi-(tempi%10)+10;
}
else
{
tempd=tempi-(tempi%10);
}
tempd=tempd/pow(10.0,accuracy+1);
return tempd;
}

float absolute(a)
float a;
{
if(a>=0)
{
return a;
}
else
{
return -a;
}
}
float BisectionMethod(degree,coeff,x1,x2,epsilon)
int degree;
float coeff[];
float x1;
float x2;
int epsilon;
{
float x3,fx1,fx3;
do
{
x3=(x1+x2)/2;
printf(" # %f # ",x3);
fx1=polynomial(degree,x1,coeff);
fx3=polynomial(degree,x3,coeff);
if(fx1*fx3<0.0)
{
x1=x3;
}
else
{
x2=x3;
}
}while((absolute(x1-x2))>epsilon&&fx3!=0.0);
return x3;
}
void main()
{
int degree=3,i,epsilon=3;
float coeff[20]={-9,-4,0,1},root=0.0,x1,x2;
clrscr();
printf( "----------------------------");
printf("\n### Bisection Method ###");
printf("\n----------------------------");
printf("\n\nEnter value for lower bound : ");
scanf("%f",&x1);
printf("Enter value for upper bound : ");
scanf("%f",&x2);
printf("Enter tolerance (accuracy) : ");
scanf("%d",&epsilon);
printf("Enter degree of the equation : ");
scanf("%d",degree);
printf("\n");
for(i=degree;i>=0;i--)
{
printf("Coefficient of x^%d : ",i);
scanf("%f",&coeff[i]);
}
root=BisectionMethod(degree,coeff,x1,x2,epsilon);
printf("\nRoot of the equation is %f",root);
getch();
}


0 Comments: