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

C examples for Data Structure:Algorithm

Description

To Find the Roots of an Equation Using the Newton Raphson Method

Demo Code

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

#define EPS  0.00001// w  w  w . j  a va2  s .c o  m
#define f(x) 17*x*x*x - 13*x*x - 7*x - 2973
#define df(x) 51*x*x - 26*x - 7

void newtonRaphson();
void main()
{
  printf ("\nEquation is: 17*x*x*x - 13*x*x - 7*x - 2973 = 0 \n\n");
  newtonRaphson();
}

void newtonRaphson()
{
  long float x1, x2, f1, f2, df;
  int i=1, iterations = 7;
  float error;
  x2 = 0;
  do {
    f2 = f(x2);
    if (f2 > 0)
      break;
    x2 += 0.01;
  } while (1);
  x1 = x2 - 0.01;
  f1 = f(x1);
  x1 = (x1 + x2) / 2;
  while (i <= iterations) {
    f1 = f(x1);
    df = df(x1);
    x2 = x1 - (f1/df);
    printf("\nThe %d th approximation, x = %f", i, x2);
    error = fabs(x2 - x1);
    if(error < EPS)
      break;
    x1 = x2;
    i++;
  }
  if(error > EPS)
    printf("Solution Doesn't Converge or No. of Iterations Insufficient.");
  printf("\nRoot,  x = %8.6f ", x2);
}

Related Tutorials