Newton Raphson Method

#include<stdio.h>
//#include<conio.h>
#include<math.h>
#include<stdlib.h>

/* Defining equation to be solved.

Change this equation to solve another problem. */

#define f(x) 3*x - cos(x) -1


/* Defining derivative of g(x).

As you change f(x), change this function also. */

#define g(x) 3 + sin(x)

void main()

{
int i= 1;

float x0, x1,h;

double f0, f1, g0;

// clrscr();

/* Inputs */

printf("\nEnter initial guess x0:\n");

scanf("%f", &x0);

printf("\n_______\n");

/* Implementing Newton Raphson Method */

printf("\ni\tx0\tf(x0)\tx1\tf(x1)\th\n");

printf("\n________\n");

do {
g0 = g(x0);

f0 = f(x0);

x1 = x0 - f0/g0;

h=x1-x0;

printf("%d\t%f\t%f\t%f\t%f\t%f\n",i,x0,f0,x1,f1,h);

x0 = x1;

f1 = f(x1);

i++;
}while(fabs(f1)>0.0001);

printf("\nRoot is: %f", x1);

// getch();

}

Comments