Tuesday, February 01, 2011

Regula Falsi method


Source Code:

#include<stdio.h>

float value_at_A;   /* equal to f(A) */
float value_at_C;   /* equal to f(C) */
float sign;         /* sign = f(C)*f(A) either < 0 or >0 */
float A;
float B;
float C;
int iterations;

/* the ploynomial whose root is to be found */
struct polynomial {
int number_of_terms;
int exponent[10];
float coefficient[10];
} poly;

float power(float x,int n) {
int i;
float pow=1;
for(i=0;i<n;i++) {
pow=pow*x; }
return pow;
}

void store_poly() {
int counter=0;
printf("\tEnter the number of terms for your polynomial .... ");
scanf("%d",&poly.number_of_terms);
while(counter<poly.number_of_terms) {
printf("\tEnter the value of coefficient for term  %d .... ",counter+1);
scanf("%f",&poly.coefficient[counter]);
printf("\tEnter the value of its exponent .... ");
scanf("%d",&poly.exponent[counter]);
counter++ ;
  }
}

void print_poly() {
int length=0;
printf("\t----------------------------------------------------------------------------------------\n");
printf("\n\tThe Entered polynomial is as follows ..... ");
while(length<poly.number_of_terms) {
printf("(%f * X^ %d) ",poly.coefficient[length],poly.exponent[length]);
if(length!= poly.number_of_terms-1)
printf("+ ");
length++ ;
}
printf(" = 0 \n");
printf("\t------------------------------------------------------------------------------------------\n");
}

void enter_boundary_values() {
printf("\n\tEnter lower boundary : ");
scanf("%f",&A);
printf("\n\tEnter upper boundary : ");
scanf("%f",&B);
if(A>B){
printf("\n\tERROR : lower boundary value must be LESS than the upper boundary value !");
enter_boundary_values(); /* recurssive call in case of error */
  }
}

float value_at(float x) { /* to calculate f(x) */
int counter=0;
float value=0.00;
while(counter<poly.number_of_terms) {
value += poly.coefficient[counter] * power(x,poly.exponent[counter]);
counter++;
 }
return value;
}

float find_root() {
int iteration=0;
while( iteration<iterations) {
  if(value_at(C)==0)
 break;
 C = (A*value_at(B)-B*value_at(A))/(value_at(B)-value_at(A)) ;
 sign = value_at(C) * value_at(A);
 if(sign<0)
 B=C;
 else A=C;
 iteration++;
 }
 return C;}

main() {
int i;
printf("\t************************************************************\n");
printf("\t              DEMONSTRATION OF REGULA-FALSI  METHOD\n");
printf("\t************************************************************\n");
printf("\t ENTER THE POLYNOMIAL  ........\n\n");
store_poly();
print_poly();
enter_boundary_values();

for(i=0;i<30;i++) {
iterations=2+i;

printf("\t=====================================================\n");
printf("\tCalculated  Root (by regula-falsi method)  approximately = %f (iterations= %d)\n",find_root(),iterations);
printf("\t====================================================\n");
 }
}

No comments:

Post a Comment

Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.