To Find the Roots of an Equation Using the Bisection Method - C Data Structure

C examples for Data Structure:Algorithm

Description

To Find the Roots of an Equation Using the Bisection Method

Demo Code

#include <stdio.h>
#include <math.h>

#define EPS 0.00001//  www  . j  a  v  a2  s .  co  m
#define F(x) (5*x*x) * log10(x) - 5.3

void bisect();

int count = 1, counter = 7;
float root = 1;

void main()
{
   printf("\nEquation:   (5*x*x) * log10(x) - 5.3 = 0");
   bisect();
}

void bisect()
{
   float x1, x2, x3, func1, func2, func3;
   x3 = 1;
   do {
      func3 = F(x3);
      if (func3 > 0) {
         break;
      }
      x3++;
   } while (1);
   x2 = x3 - 1;
   do {
      func2 = F(x2);
      if (func2 < 0) {
         break;
      }
      x3--;
   } while (1);
   while (count <= counter) {
      x1 = (x2 + x3) / 2.0;
      func1 = F(x1);
      if (func1 == 0) {
         root = x1;
      }
      if (func1 * func2  <0) {
         x3 = x1;
      }
      else {
         x2 = x1;
         func2 = func1;
      }
      printf("\nIteration No. %d", count);
      printf("      :     Root, x = %f", x1);
      if (fabs((x2 - x3) / x2) < EPS) {
         printf("\n\nTotal No. of Iterations:  %d", count);
         printf("\nRoot, x = %f", x1);
         printf("\n\nThank you.\n");
         return ;
      }
      count++;
   }
   printf("\n\nTotal No. of Iterations = %d", count - 1);
   printf("\nRoot, x = %8.6f", x1);
}

Related Tutorials