Tuesday, February 01, 2011

Iterative method for solving non-linear equations


 Source:
 #include<stdio.h>
 #include<stdlib.h>
 #include<conio.h>
 #include<math.h>

 #define f(x) ((log10(x)+7)/2)
 #define f1(x) (1/(x*log (10)*2))


 float error;
 void Iterative_Driver(float);
 void Iterative_Method(float);                

 void main()
 {
      long float x;
      int d;
      clrscr();
      printf("\nEnter the approximate root: - ");
      scanf("%lf",&x);
      printf("\nEnter the degree of precision required: - ");
      scanf("%d",&d);
      error=0.5*pow(10,-d);
      Iterative_Driver(x);
      getch();

 }

/*function to check for conditions and then calls iterative method*/
 void Iterative_Driver(float approot)
 {
       if(f(approot)==0.0f)
       {
         printf("\nThe no. entered is the root\n");
         return;
       }
       if(fabs(f1(approot))>=1.0)
       {
         printf("\nCondition of convergence not satisfied.Try again!\n");
         return;
       }
       else
        Iterative_Method(approot);
 }

/*function to demonstrate the repeated substitution method*/
void Iterative_Method(float root)
{
  float Xi,Xi_1,Ri,Ri_1;
  int count=0,flag=1;
  printf("\n\nIteration(i)        Xi                  Relative Error      Order of Convergence\n");
  printf("========================================\n\n\n");
  do
  {
       if(count==0)
        Xi=root;
       else
        Xi=f(Xi_1);

       printf("%-20d",count+1);
       printf("%-20lf",Xi);
       if(count)
       {
           printf("%-20lf",fabs(Xi-Xi_1));
           if(fabs(Xi-Xi_1)<error)
            flag=0;
       }
       else
           printf("%-20s","-----");
       if(count>1)
           printf("%-18lf",log(fabs(Xi-Xi_1))/log(Ri_1));
       else
           printf("%-18s","-----");
       if(count>=1)
           Ri_1=fabs(Xi-Xi_1);
       printf("\n\n");
       Xi_1=Xi;
       count++;
       if(!flag)
          break;
  }while(1);
  printf("\n\nThe root is : %.4f",Xi);
}
Output
 

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.