To Find the Roots of an Equation Using Muller's Method - C Data Structure

C examples for Data Structure:Algorithm

Description

To Find the Roots of an Equation Using Muller's Method

Demo Code

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

#define EPS  0.00001//ww w .j  a  va2  s .  c om

float f(float x)
{
  return (x*x*x)-(2*x)-5;
}

int main ()
{
  int i, itr, maxItr;
  float x[4], m, n, p, q, r;
  printf("\nEquation: x*x*x - 2*x - 5 = 0  \n");

  x[0] = 3;
  x[1] = 4;
  x[2] = 6 ;
  maxItr = 10;
  
  for (itr = 1; itr <= maxItr; itr++)    {
    m = (x[2] - x[1]) / (x[1] - x[0]);
    n = (x[2] - x[0]) / (x[1] - x[0]);
    p = f(x[0])*m*m - f(x[1])*n*n + f(x[2])*(n+m);
    q = sqrt ((p*p - 4*f(x[2])*n*m*(f(x[0])*m - f(x[1])*n + f(x[2]))));
    if (p < 0)
      r = (2*f(x[2])*n)/(-p+q);
    else
      r = (2*f(x[2])*n)/(-p-q);
    x[3] = x[2] + r*(x[2] - x[1]);
    printf("Iteration No. : %d,      x = %8.6f\n", itr, x[3]);
    if (fabs (x[3] - x[2]) < EPS) {
      printf("\nTotal No. of Iterations: %d\n", itr);
      printf("\Root, x = %8.6f\n", x[3]);
      printf("Thank you.\n");
      return 0;
    }
        for (i=0; i<3; i++)
            x[i] = x[i+1];
  }
  printf("\nSolution Doesn't Converge or Iterations are Insufficient.\n");
  return(0);
}

Related Tutorials